babylon.no-module.max.js 4.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. /** @hidden */
  163. this._bonesComputationForcedToCPU = false;
  164. this._uniformBuffersNames = {};
  165. this._isReady = false;
  166. this._compilationError = "";
  167. this.name = baseName;
  168. if (attributesNamesOrOptions.attributes) {
  169. var options = attributesNamesOrOptions;
  170. this._engine = uniformsNamesOrEngine;
  171. this._attributesNames = options.attributes;
  172. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  173. this._samplers = options.samplers.slice();
  174. this.defines = options.defines;
  175. this.onError = options.onError;
  176. this.onCompiled = options.onCompiled;
  177. this._fallbacks = options.fallbacks;
  178. this._indexParameters = options.indexParameters;
  179. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  180. if (options.uniformBuffersNames) {
  181. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  182. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  183. }
  184. }
  185. }
  186. else {
  187. this._engine = engine;
  188. this.defines = defines;
  189. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  190. this._samplers = samplers ? samplers.slice() : [];
  191. this._attributesNames = attributesNamesOrOptions;
  192. this.onError = onError;
  193. this.onCompiled = onCompiled;
  194. this._indexParameters = indexParameters;
  195. this._fallbacks = fallbacks;
  196. }
  197. this.uniqueId = Effect._uniqueIdSeed++;
  198. var vertexSource;
  199. var fragmentSource;
  200. if (baseName.vertexElement) {
  201. vertexSource = document.getElementById(baseName.vertexElement);
  202. if (!vertexSource) {
  203. vertexSource = baseName.vertexElement;
  204. }
  205. }
  206. else {
  207. vertexSource = baseName.vertex || baseName;
  208. }
  209. if (baseName.fragmentElement) {
  210. fragmentSource = document.getElementById(baseName.fragmentElement);
  211. if (!fragmentSource) {
  212. fragmentSource = baseName.fragmentElement;
  213. }
  214. }
  215. else {
  216. fragmentSource = baseName.fragment || baseName;
  217. }
  218. this._loadVertexShader(vertexSource, function (vertexCode) {
  219. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  220. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  221. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  222. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  223. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  224. if (baseName) {
  225. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  226. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  227. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  228. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  229. }
  230. else {
  231. _this._vertexSourceCode = migratedVertexCode;
  232. _this._fragmentSourceCode = migratedFragmentCode;
  233. }
  234. _this._prepareEffect();
  235. });
  236. });
  237. });
  238. });
  239. });
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @hidden */
  348. Effect.prototype._loadVertexShader = function (vertex, callback) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. callback(vertexCode);
  354. return;
  355. }
  356. }
  357. // Base64 encoded ?
  358. if (vertex.substr(0, 7) === "base64:") {
  359. var vertexBinary = window.atob(vertex.substr(7));
  360. callback(vertexBinary);
  361. return;
  362. }
  363. // Is in local store ?
  364. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  365. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  366. return;
  367. }
  368. var vertexShaderUrl;
  369. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  370. vertexShaderUrl = vertex;
  371. }
  372. else {
  373. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  374. }
  375. // Vertex shader
  376. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  377. };
  378. /** @hidden */
  379. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  380. if (BABYLON.Tools.IsWindowObjectExist()) {
  381. // DOM element ?
  382. if (fragment instanceof HTMLElement) {
  383. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  384. callback(fragmentCode);
  385. return;
  386. }
  387. }
  388. // Base64 encoded ?
  389. if (fragment.substr(0, 7) === "base64:") {
  390. var fragmentBinary = window.atob(fragment.substr(7));
  391. callback(fragmentBinary);
  392. return;
  393. }
  394. // Is in local store ?
  395. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  396. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  397. return;
  398. }
  399. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  400. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  401. return;
  402. }
  403. var fragmentShaderUrl;
  404. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  405. fragmentShaderUrl = fragment;
  406. }
  407. else {
  408. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  409. }
  410. // Fragment shader
  411. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  412. };
  413. /** @hidden */
  414. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  415. // Rebuild shaders source code
  416. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  417. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  418. vertexCode = prefix + vertexCode;
  419. fragmentCode = prefix + fragmentCode;
  420. // Number lines of shaders source code
  421. var i = 2;
  422. var regex = /\n/gm;
  423. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  424. i = 2;
  425. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  426. // Dump shaders name and formatted source code
  427. if (this.name.vertexElement) {
  428. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  429. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  430. }
  431. else if (this.name.vertex) {
  432. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  433. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  434. }
  435. else {
  436. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  437. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  438. }
  439. };
  440. ;
  441. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  442. var preparedSourceCode = this._processPrecision(sourceCode);
  443. if (this._engine.webGLVersion == 1) {
  444. callback(preparedSourceCode);
  445. return;
  446. }
  447. // Already converted
  448. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  449. callback(preparedSourceCode.replace("#version 300 es", ""));
  450. return;
  451. }
  452. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  453. // Remove extensions
  454. // #extension GL_OES_standard_derivatives : enable
  455. // #extension GL_EXT_shader_texture_lod : enable
  456. // #extension GL_EXT_frag_depth : enable
  457. // #extension GL_EXT_draw_buffers : require
  458. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  459. var result = preparedSourceCode.replace(regex, "");
  460. // Migrate to GLSL v300
  461. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  462. result = result.replace(/attribute[ \t]/g, "in ");
  463. result = result.replace(/[ \t]attribute/g, " in");
  464. if (isFragment) {
  465. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  466. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  467. result = result.replace(/texture2D\s*\(/g, "texture(");
  468. result = result.replace(/textureCube\s*\(/g, "texture(");
  469. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  470. result = result.replace(/gl_FragColor/g, "glFragColor");
  471. result = result.replace(/gl_FragData/g, "glFragData");
  472. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  473. }
  474. callback(result);
  475. };
  476. Effect.prototype._processIncludes = function (sourceCode, callback) {
  477. var _this = this;
  478. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  479. var match = regex.exec(sourceCode);
  480. var returnValue = new String(sourceCode);
  481. while (match != null) {
  482. var includeFile = match[1];
  483. // Uniform declaration
  484. if (includeFile.indexOf("__decl__") !== -1) {
  485. includeFile = includeFile.replace(/__decl__/, "");
  486. if (this._engine.supportsUniformBuffers) {
  487. includeFile = includeFile.replace(/Vertex/, "Ubo");
  488. includeFile = includeFile.replace(/Fragment/, "Ubo");
  489. }
  490. includeFile = includeFile + "Declaration";
  491. }
  492. if (Effect.IncludesShadersStore[includeFile]) {
  493. // Substitution
  494. var includeContent = Effect.IncludesShadersStore[includeFile];
  495. if (match[2]) {
  496. var splits = match[3].split(",");
  497. for (var index = 0; index < splits.length; index += 2) {
  498. var source = new RegExp(splits[index], "g");
  499. var dest = splits[index + 1];
  500. includeContent = includeContent.replace(source, dest);
  501. }
  502. }
  503. if (match[4]) {
  504. var indexString = match[5];
  505. if (indexString.indexOf("..") !== -1) {
  506. var indexSplits = indexString.split("..");
  507. var minIndex = parseInt(indexSplits[0]);
  508. var maxIndex = parseInt(indexSplits[1]);
  509. var sourceIncludeContent = includeContent.slice(0);
  510. includeContent = "";
  511. if (isNaN(maxIndex)) {
  512. maxIndex = this._indexParameters[indexSplits[1]];
  513. }
  514. for (var i = minIndex; i < maxIndex; i++) {
  515. if (!this._engine.supportsUniformBuffers) {
  516. // Ubo replacement
  517. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  518. return p1 + "{X}";
  519. });
  520. }
  521. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  522. }
  523. }
  524. else {
  525. if (!this._engine.supportsUniformBuffers) {
  526. // Ubo replacement
  527. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  528. return p1 + "{X}";
  529. });
  530. }
  531. includeContent = includeContent.replace(/\{X\}/g, indexString);
  532. }
  533. }
  534. // Replace
  535. returnValue = returnValue.replace(match[0], includeContent);
  536. }
  537. else {
  538. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  539. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  540. Effect.IncludesShadersStore[includeFile] = fileContent;
  541. _this._processIncludes(returnValue, callback);
  542. });
  543. return;
  544. }
  545. match = regex.exec(sourceCode);
  546. }
  547. callback(returnValue);
  548. };
  549. Effect.prototype._processPrecision = function (source) {
  550. if (source.indexOf("precision highp float") === -1) {
  551. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  552. source = "precision mediump float;\n" + source;
  553. }
  554. else {
  555. source = "precision highp float;\n" + source;
  556. }
  557. }
  558. else {
  559. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  560. source = source.replace("precision highp float", "precision mediump float");
  561. }
  562. }
  563. return source;
  564. };
  565. /**
  566. * Recompiles the webGL program
  567. * @param vertexSourceCode The source code for the vertex shader.
  568. * @param fragmentSourceCode The source code for the fragment shader.
  569. * @param onCompiled Callback called when completed.
  570. * @param onError Callback called on error.
  571. */
  572. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  573. var _this = this;
  574. this._isReady = false;
  575. this._vertexSourceCodeOverride = vertexSourceCode;
  576. this._fragmentSourceCodeOverride = fragmentSourceCode;
  577. this.onError = function (effect, error) {
  578. if (onError) {
  579. onError(error);
  580. }
  581. };
  582. this.onCompiled = function () {
  583. var scenes = _this.getEngine().scenes;
  584. for (var i = 0; i < scenes.length; i++) {
  585. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  586. }
  587. if (onCompiled) {
  588. onCompiled(_this._program);
  589. }
  590. };
  591. this._fallbacks = null;
  592. this._prepareEffect();
  593. };
  594. /**
  595. * Gets the uniform locations of the the specified variable names
  596. * @param names THe names of the variables to lookup.
  597. * @returns Array of locations in the same order as variable names.
  598. */
  599. Effect.prototype.getSpecificUniformLocations = function (names) {
  600. var engine = this._engine;
  601. return engine.getUniforms(this._program, names);
  602. };
  603. /**
  604. * Prepares the effect
  605. */
  606. Effect.prototype._prepareEffect = function () {
  607. var attributesNames = this._attributesNames;
  608. var defines = this.defines;
  609. var fallbacks = this._fallbacks;
  610. this._valueCache = {};
  611. var previousProgram = this._program;
  612. try {
  613. var engine = this._engine;
  614. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  615. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  616. }
  617. else {
  618. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  619. }
  620. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  621. if (engine.supportsUniformBuffers) {
  622. for (var name in this._uniformBuffersNames) {
  623. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  624. }
  625. }
  626. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  627. this._attributes = engine.getAttributes(this._program, attributesNames);
  628. var index;
  629. for (index = 0; index < this._samplers.length; index++) {
  630. var sampler = this.getUniform(this._samplers[index]);
  631. if (sampler == null) {
  632. this._samplers.splice(index, 1);
  633. index--;
  634. }
  635. }
  636. engine.bindSamplers(this);
  637. this._compilationError = "";
  638. this._isReady = true;
  639. if (this.onCompiled) {
  640. this.onCompiled(this);
  641. }
  642. this.onCompileObservable.notifyObservers(this);
  643. this.onCompileObservable.clear();
  644. // Unbind mesh reference in fallbacks
  645. if (this._fallbacks) {
  646. this._fallbacks.unBindMesh();
  647. }
  648. if (previousProgram) {
  649. this.getEngine()._deleteProgram(previousProgram);
  650. }
  651. }
  652. catch (e) {
  653. this._compilationError = e.message;
  654. // Let's go through fallbacks then
  655. BABYLON.Tools.Error("Unable to compile effect:");
  656. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  657. return " " + uniform;
  658. }));
  659. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  660. return " " + attribute;
  661. }));
  662. BABYLON.Tools.Error("Error: " + this._compilationError);
  663. if (previousProgram) {
  664. this._program = previousProgram;
  665. this._isReady = true;
  666. if (this.onError) {
  667. this.onError(this, this._compilationError);
  668. }
  669. this.onErrorObservable.notifyObservers(this);
  670. }
  671. if (fallbacks && fallbacks.isMoreFallbacks) {
  672. BABYLON.Tools.Error("Trying next fallback.");
  673. this.defines = fallbacks.reduce(this.defines, this);
  674. this._prepareEffect();
  675. }
  676. else { // Sorry we did everything we can
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. this.onErrorObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. }
  687. }
  688. };
  689. Object.defineProperty(Effect.prototype, "isSupported", {
  690. /**
  691. * Checks if the effect is supported. (Must be called after compilation)
  692. */
  693. get: function () {
  694. return this._compilationError === "";
  695. },
  696. enumerable: true,
  697. configurable: true
  698. });
  699. /**
  700. * Binds a texture to the engine to be used as output of the shader.
  701. * @param channel Name of the output variable.
  702. * @param texture Texture to bind.
  703. */
  704. Effect.prototype._bindTexture = function (channel, texture) {
  705. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  706. };
  707. /**
  708. * Sets a texture on the engine to be used in the shader.
  709. * @param channel Name of the sampler variable.
  710. * @param texture Texture to set.
  711. */
  712. Effect.prototype.setTexture = function (channel, texture) {
  713. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  714. };
  715. /**
  716. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  717. * @param channel Name of the sampler variable.
  718. * @param texture Texture to set.
  719. */
  720. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  721. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  722. };
  723. /**
  724. * Sets an array of textures on the engine to be used in the shader.
  725. * @param channel Name of the variable.
  726. * @param textures Textures to set.
  727. */
  728. Effect.prototype.setTextureArray = function (channel, textures) {
  729. if (this._samplers.indexOf(channel + "Ex") === -1) {
  730. var initialPos = this._samplers.indexOf(channel);
  731. for (var index = 1; index < textures.length; index++) {
  732. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  733. }
  734. }
  735. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  736. };
  737. /**
  738. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  739. * @param channel Name of the sampler variable.
  740. * @param postProcess Post process to get the input texture from.
  741. */
  742. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  743. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  744. };
  745. /**
  746. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  747. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  748. * @param channel Name of the sampler variable.
  749. * @param postProcess Post process to get the output texture from.
  750. */
  751. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  752. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  753. };
  754. /** @hidden */
  755. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  756. var cache = this._valueCache[uniformName];
  757. var flag = matrix.updateFlag;
  758. if (cache !== undefined && cache === flag) {
  759. return false;
  760. }
  761. this._valueCache[uniformName] = flag;
  762. return true;
  763. };
  764. /** @hidden */
  765. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  766. var cache = this._valueCache[uniformName];
  767. if (!cache) {
  768. cache = [x, y];
  769. this._valueCache[uniformName] = cache;
  770. return true;
  771. }
  772. var changed = false;
  773. if (cache[0] !== x) {
  774. cache[0] = x;
  775. changed = true;
  776. }
  777. if (cache[1] !== y) {
  778. cache[1] = y;
  779. changed = true;
  780. }
  781. return changed;
  782. };
  783. /** @hidden */
  784. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  785. var cache = this._valueCache[uniformName];
  786. if (!cache) {
  787. cache = [x, y, z];
  788. this._valueCache[uniformName] = cache;
  789. return true;
  790. }
  791. var changed = false;
  792. if (cache[0] !== x) {
  793. cache[0] = x;
  794. changed = true;
  795. }
  796. if (cache[1] !== y) {
  797. cache[1] = y;
  798. changed = true;
  799. }
  800. if (cache[2] !== z) {
  801. cache[2] = z;
  802. changed = true;
  803. }
  804. return changed;
  805. };
  806. /** @hidden */
  807. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  808. var cache = this._valueCache[uniformName];
  809. if (!cache) {
  810. cache = [x, y, z, w];
  811. this._valueCache[uniformName] = cache;
  812. return true;
  813. }
  814. var changed = false;
  815. if (cache[0] !== x) {
  816. cache[0] = x;
  817. changed = true;
  818. }
  819. if (cache[1] !== y) {
  820. cache[1] = y;
  821. changed = true;
  822. }
  823. if (cache[2] !== z) {
  824. cache[2] = z;
  825. changed = true;
  826. }
  827. if (cache[3] !== w) {
  828. cache[3] = w;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /**
  834. * Binds a buffer to a uniform.
  835. * @param buffer Buffer to bind.
  836. * @param name Name of the uniform variable to bind to.
  837. */
  838. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  839. var bufferName = this._uniformBuffersNames[name];
  840. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  841. return;
  842. }
  843. Effect._baseCache[bufferName] = buffer;
  844. this._engine.bindUniformBufferBase(buffer, bufferName);
  845. };
  846. /**
  847. * Binds block to a uniform.
  848. * @param blockName Name of the block to bind.
  849. * @param index Index to bind.
  850. */
  851. Effect.prototype.bindUniformBlock = function (blockName, index) {
  852. this._engine.bindUniformBlock(this._program, blockName, index);
  853. };
  854. /**
  855. * Sets an interger value on a uniform variable.
  856. * @param uniformName Name of the variable.
  857. * @param value Value to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setInt = function (uniformName, value) {
  861. var cache = this._valueCache[uniformName];
  862. if (cache !== undefined && cache === value)
  863. return this;
  864. this._valueCache[uniformName] = value;
  865. this._engine.setInt(this.getUniform(uniformName), value);
  866. return this;
  867. };
  868. /**
  869. * Sets an int array on a uniform variable.
  870. * @param uniformName Name of the variable.
  871. * @param array array to be set.
  872. * @returns this effect.
  873. */
  874. Effect.prototype.setIntArray = function (uniformName, array) {
  875. this._valueCache[uniformName] = null;
  876. this._engine.setIntArray(this.getUniform(uniformName), array);
  877. return this;
  878. };
  879. /**
  880. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  881. * @param uniformName Name of the variable.
  882. * @param array array to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setIntArray2 = function (uniformName, array) {
  886. this._valueCache[uniformName] = null;
  887. this._engine.setIntArray2(this.getUniform(uniformName), array);
  888. return this;
  889. };
  890. /**
  891. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray3 = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray3(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray4 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray4(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * Sets an float array on a uniform variable.
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setFloatArray = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setFloatArray(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * Sets an array on a uniform variable.
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setArray = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setArray(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setArray2 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setArray2(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray3 = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray3(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray4 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray4(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * Sets matrices on a uniform variable.
  1002. * @param uniformName Name of the variable.
  1003. * @param matrices matrices to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1007. if (!matrices) {
  1008. return this;
  1009. }
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1012. return this;
  1013. };
  1014. /**
  1015. * Sets matrix on a uniform variable.
  1016. * @param uniformName Name of the variable.
  1017. * @param matrix matrix to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1021. if (this._cacheMatrix(uniformName, matrix)) {
  1022. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1023. }
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1039. * @param uniformName Name of the variable.
  1040. * @param matrix matrix to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1044. this._valueCache[uniformName] = null;
  1045. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1046. return this;
  1047. };
  1048. /**
  1049. * Sets a float on a uniform variable.
  1050. * @param uniformName Name of the variable.
  1051. * @param value value to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setFloat = function (uniformName, value) {
  1055. var cache = this._valueCache[uniformName];
  1056. if (cache !== undefined && cache === value)
  1057. return this;
  1058. this._valueCache[uniformName] = value;
  1059. this._engine.setFloat(this.getUniform(uniformName), value);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets a boolean on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param bool value to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setBool = function (uniformName, bool) {
  1069. var cache = this._valueCache[uniformName];
  1070. if (cache !== undefined && cache === bool)
  1071. return this;
  1072. this._valueCache[uniformName] = bool;
  1073. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a Vector2 on a uniform variable.
  1078. * @param uniformName Name of the variable.
  1079. * @param vector2 vector2 to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1083. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1084. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1085. }
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a float2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param x First float in float2.
  1092. * @param y Second float in float2.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1096. if (this._cacheFloat2(uniformName, x, y)) {
  1097. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1098. }
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a Vector3 on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param vector3 Value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1108. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1109. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param x First float in float3.
  1117. * @param y Second float in float3.
  1118. * @param z Third float in float3.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1122. if (this._cacheFloat3(uniformName, x, y, z)) {
  1123. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a Vector4 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param vector4 Value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1134. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1135. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a float4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param x First float in float4.
  1143. * @param y Second float in float4.
  1144. * @param z Third float in float4.
  1145. * @param w Fourth float in float4.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1149. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1150. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Color3 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param color3 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setColor3 = function (uniformName, color3) {
  1161. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1162. this._engine.setColor3(this.getUniform(uniformName), color3);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @param alpha Alpha value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1174. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1175. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a Color4 on a uniform variable
  1181. * @param uniformName defines the name of the variable
  1182. * @param color4 defines the value to be set
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1186. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1187. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Resets the cache of effects.
  1193. */
  1194. Effect.ResetCache = function () {
  1195. Effect._baseCache = {};
  1196. };
  1197. Effect._uniqueIdSeed = 0;
  1198. Effect._baseCache = {};
  1199. /**
  1200. * Store of each shader (The can be looked up using effect.key)
  1201. */
  1202. Effect.ShadersStore = {};
  1203. /**
  1204. * Store of each included file for a shader (The can be looked up using effect.key)
  1205. */
  1206. Effect.IncludesShadersStore = {};
  1207. return Effect;
  1208. }());
  1209. BABYLON.Effect = Effect;
  1210. })(BABYLON || (BABYLON = {}));
  1211. //# sourceMappingURL=babylon.effect.js.map
  1212. //# sourceMappingURL=babylon.types.js.map
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. var BABYLON;
  1262. (function (BABYLON) {
  1263. var PointerEventTypes = /** @class */ (function () {
  1264. function PointerEventTypes() {
  1265. }
  1266. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1267. get: function () {
  1268. return PointerEventTypes._POINTERDOWN;
  1269. },
  1270. enumerable: true,
  1271. configurable: true
  1272. });
  1273. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1274. get: function () {
  1275. return PointerEventTypes._POINTERUP;
  1276. },
  1277. enumerable: true,
  1278. configurable: true
  1279. });
  1280. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1281. get: function () {
  1282. return PointerEventTypes._POINTERMOVE;
  1283. },
  1284. enumerable: true,
  1285. configurable: true
  1286. });
  1287. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1288. get: function () {
  1289. return PointerEventTypes._POINTERWHEEL;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERPICK;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERTAP;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERDOUBLETAP;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. PointerEventTypes._POINTERDOWN = 0x01;
  1316. PointerEventTypes._POINTERUP = 0x02;
  1317. PointerEventTypes._POINTERMOVE = 0x04;
  1318. PointerEventTypes._POINTERWHEEL = 0x08;
  1319. PointerEventTypes._POINTERPICK = 0x10;
  1320. PointerEventTypes._POINTERTAP = 0x20;
  1321. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1322. return PointerEventTypes;
  1323. }());
  1324. BABYLON.PointerEventTypes = PointerEventTypes;
  1325. var PointerInfoBase = /** @class */ (function () {
  1326. function PointerInfoBase(type, event) {
  1327. this.type = type;
  1328. this.event = event;
  1329. }
  1330. return PointerInfoBase;
  1331. }());
  1332. BABYLON.PointerInfoBase = PointerInfoBase;
  1333. /**
  1334. * This class is used to store pointer related info for the onPrePointerObservable event.
  1335. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1336. */
  1337. var PointerInfoPre = /** @class */ (function (_super) {
  1338. __extends(PointerInfoPre, _super);
  1339. function PointerInfoPre(type, event, localX, localY) {
  1340. var _this = _super.call(this, type, event) || this;
  1341. /**
  1342. * Ray from a pointer if availible (eg. 6dof controller)
  1343. */
  1344. _this.ray = null;
  1345. _this.skipOnPointerObservable = false;
  1346. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1347. return _this;
  1348. }
  1349. return PointerInfoPre;
  1350. }(PointerInfoBase));
  1351. BABYLON.PointerInfoPre = PointerInfoPre;
  1352. /**
  1353. * This type contains all the data related to a pointer event in Babylon.js.
  1354. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1355. */
  1356. var PointerInfo = /** @class */ (function (_super) {
  1357. __extends(PointerInfo, _super);
  1358. function PointerInfo(type, event, pickInfo) {
  1359. var _this = _super.call(this, type, event) || this;
  1360. _this.pickInfo = pickInfo;
  1361. return _this;
  1362. }
  1363. return PointerInfo;
  1364. }(PointerInfoBase));
  1365. BABYLON.PointerInfo = PointerInfo;
  1366. })(BABYLON || (BABYLON = {}));
  1367. //# sourceMappingURL=babylon.pointerEvents.js.map
  1368. var BABYLON;
  1369. (function (BABYLON) {
  1370. BABYLON.ToGammaSpace = 1 / 2.2;
  1371. BABYLON.ToLinearSpace = 2.2;
  1372. BABYLON.Epsilon = 0.001;
  1373. /**
  1374. * Class used to hold a RBG color
  1375. */
  1376. var Color3 = /** @class */ (function () {
  1377. /**
  1378. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1379. * @param r defines the red component (between 0 and 1, default is 0)
  1380. * @param g defines the green component (between 0 and 1, default is 0)
  1381. * @param b defines the blue component (between 0 and 1, default is 0)
  1382. */
  1383. function Color3(
  1384. /**
  1385. * Defines the red component (between 0 and 1, default is 0)
  1386. */
  1387. r,
  1388. /**
  1389. * Defines the green component (between 0 and 1, default is 0)
  1390. */
  1391. g,
  1392. /**
  1393. * Defines the blue component (between 0 and 1, default is 0)
  1394. */
  1395. b) {
  1396. if (r === void 0) { r = 0; }
  1397. if (g === void 0) { g = 0; }
  1398. if (b === void 0) { b = 0; }
  1399. this.r = r;
  1400. this.g = g;
  1401. this.b = b;
  1402. }
  1403. /**
  1404. * Creates a string with the Color3 current values
  1405. * @returns the string representation of the Color3 object
  1406. */
  1407. Color3.prototype.toString = function () {
  1408. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1409. };
  1410. /**
  1411. * Returns the string "Color3"
  1412. * @returns "Color3"
  1413. */
  1414. Color3.prototype.getClassName = function () {
  1415. return "Color3";
  1416. };
  1417. /**
  1418. * Compute the Color3 hash code
  1419. * @returns an unique number that can be used to hash Color3 objects
  1420. */
  1421. Color3.prototype.getHashCode = function () {
  1422. var hash = this.r || 0;
  1423. hash = (hash * 397) ^ (this.g || 0);
  1424. hash = (hash * 397) ^ (this.b || 0);
  1425. return hash;
  1426. };
  1427. // Operators
  1428. /**
  1429. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1430. * @param array defines the array where to store the r,g,b components
  1431. * @param index defines an optional index in the target array to define where to start storing values
  1432. * @returns the current Color3 object
  1433. */
  1434. Color3.prototype.toArray = function (array, index) {
  1435. if (index === undefined) {
  1436. index = 0;
  1437. }
  1438. array[index] = this.r;
  1439. array[index + 1] = this.g;
  1440. array[index + 2] = this.b;
  1441. return this;
  1442. };
  1443. /**
  1444. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1445. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1446. * @returns a new {BABYLON.Color4} object
  1447. */
  1448. Color3.prototype.toColor4 = function (alpha) {
  1449. if (alpha === void 0) { alpha = 1; }
  1450. return new Color4(this.r, this.g, this.b, alpha);
  1451. };
  1452. /**
  1453. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1454. * @returns the new array
  1455. */
  1456. Color3.prototype.asArray = function () {
  1457. var result = new Array();
  1458. this.toArray(result, 0);
  1459. return result;
  1460. };
  1461. /**
  1462. * Returns the luminance value
  1463. * @returns a float value
  1464. */
  1465. Color3.prototype.toLuminance = function () {
  1466. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1467. };
  1468. /**
  1469. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1470. * @param otherColor defines the second operand
  1471. * @returns the new Color3 object
  1472. */
  1473. Color3.prototype.multiply = function (otherColor) {
  1474. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1475. };
  1476. /**
  1477. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1478. * @param otherColor defines the second operand
  1479. * @param result defines the Color3 object where to store the result
  1480. * @returns the current Color3
  1481. */
  1482. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1483. result.r = this.r * otherColor.r;
  1484. result.g = this.g * otherColor.g;
  1485. result.b = this.b * otherColor.b;
  1486. return this;
  1487. };
  1488. /**
  1489. * Determines equality between Color3 objects
  1490. * @param otherColor defines the second operand
  1491. * @returns true if the rgb values are equal to the given ones
  1492. */
  1493. Color3.prototype.equals = function (otherColor) {
  1494. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1495. };
  1496. /**
  1497. * Determines equality between the current Color3 object and a set of r,b,g values
  1498. * @param r defines the red component to check
  1499. * @param g defines the green component to check
  1500. * @param b defines the blue component to check
  1501. * @returns true if the rgb values are equal to the given ones
  1502. */
  1503. Color3.prototype.equalsFloats = function (r, g, b) {
  1504. return this.r === r && this.g === g && this.b === b;
  1505. };
  1506. /**
  1507. * Multiplies in place each rgb value by scale
  1508. * @param scale defines the scaling factor
  1509. * @returns the updated Color3
  1510. */
  1511. Color3.prototype.scale = function (scale) {
  1512. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1513. };
  1514. /**
  1515. * Multiplies the rgb values by scale and stores the result into "result"
  1516. * @param scale defines the scaling factor
  1517. * @param result defines the Color3 object where to store the result
  1518. * @returns the unmodified current Color3
  1519. */
  1520. Color3.prototype.scaleToRef = function (scale, result) {
  1521. result.r = this.r * scale;
  1522. result.g = this.g * scale;
  1523. result.b = this.b * scale;
  1524. return this;
  1525. };
  1526. /**
  1527. * Scale the current Color3 values by a factor and add the result to a given Color3
  1528. * @param scale defines the scale factor
  1529. * @param result defines color to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1533. result.r += this.r * scale;
  1534. result.g += this.g * scale;
  1535. result.b += this.b * scale;
  1536. return this;
  1537. };
  1538. /**
  1539. * Clamps the rgb values by the min and max values and stores the result into "result"
  1540. * @param min defines minimum clamping value (default is 0)
  1541. * @param max defines maximum clamping value (default is 1)
  1542. * @param result defines color to store the result into
  1543. * @returns the original Color3
  1544. */
  1545. Color3.prototype.clampToRef = function (min, max, result) {
  1546. if (min === void 0) { min = 0; }
  1547. if (max === void 0) { max = 1; }
  1548. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1549. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1550. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1551. return this;
  1552. };
  1553. /**
  1554. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1555. * @param otherColor defines the second operand
  1556. * @returns the new Color3
  1557. */
  1558. Color3.prototype.add = function (otherColor) {
  1559. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1560. };
  1561. /**
  1562. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1563. * @param otherColor defines the second operand
  1564. * @param result defines Color3 object to store the result into
  1565. * @returns the unmodified current Color3
  1566. */
  1567. Color3.prototype.addToRef = function (otherColor, result) {
  1568. result.r = this.r + otherColor.r;
  1569. result.g = this.g + otherColor.g;
  1570. result.b = this.b + otherColor.b;
  1571. return this;
  1572. };
  1573. /**
  1574. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.subtract = function (otherColor) {
  1579. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.subtractToRef = function (otherColor, result) {
  1588. result.r = this.r - otherColor.r;
  1589. result.g = this.g - otherColor.g;
  1590. result.b = this.b - otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Copy the current object
  1595. * @returns a new Color3 copied the current one
  1596. */
  1597. Color3.prototype.clone = function () {
  1598. return new Color3(this.r, this.g, this.b);
  1599. };
  1600. /**
  1601. * Copies the rgb values from the source in the current Color3
  1602. * @param source defines the source Color3 object
  1603. * @returns the updated Color3 object
  1604. */
  1605. Color3.prototype.copyFrom = function (source) {
  1606. this.r = source.r;
  1607. this.g = source.g;
  1608. this.b = source.b;
  1609. return this;
  1610. };
  1611. /**
  1612. * Updates the Color3 rgb values from the given floats
  1613. * @param r defines the red component to read from
  1614. * @param g defines the green component to read from
  1615. * @param b defines the blue component to read from
  1616. * @returns the current Color3 object
  1617. */
  1618. Color3.prototype.copyFromFloats = function (r, g, b) {
  1619. this.r = r;
  1620. this.g = g;
  1621. this.b = b;
  1622. return this;
  1623. };
  1624. /**
  1625. * Updates the Color3 rgb values from the given floats
  1626. * @param r defines the red component to read from
  1627. * @param g defines the green component to read from
  1628. * @param b defines the blue component to read from
  1629. * @returns the current Color3 object
  1630. */
  1631. Color3.prototype.set = function (r, g, b) {
  1632. return this.copyFromFloats(r, g, b);
  1633. };
  1634. /**
  1635. * Compute the Color3 hexadecimal code as a string
  1636. * @returns a string containing the hexadecimal representation of the Color3 object
  1637. */
  1638. Color3.prototype.toHexString = function () {
  1639. var intR = (this.r * 255) | 0;
  1640. var intG = (this.g * 255) | 0;
  1641. var intB = (this.b * 255) | 0;
  1642. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1643. };
  1644. /**
  1645. * Computes a new Color3 converted from the current one to linear space
  1646. * @returns a new Color3 object
  1647. */
  1648. Color3.prototype.toLinearSpace = function () {
  1649. var convertedColor = new Color3();
  1650. this.toLinearSpaceToRef(convertedColor);
  1651. return convertedColor;
  1652. };
  1653. /**
  1654. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1655. * @param convertedColor defines the Color3 object where to store the linear space version
  1656. * @returns the unmodified Color3
  1657. */
  1658. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1659. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1660. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1661. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1662. return this;
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to gamma space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toGammaSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toGammaSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the gamma space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1682. return this;
  1683. };
  1684. // Statics
  1685. /**
  1686. * Creates a new Color3 from the string containing valid hexadecimal values
  1687. * @param hex defines a string containing valid hexadecimal values
  1688. * @returns a new Color3 object
  1689. */
  1690. Color3.FromHexString = function (hex) {
  1691. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1692. return new Color3(0, 0, 0);
  1693. }
  1694. var r = parseInt(hex.substring(1, 3), 16);
  1695. var g = parseInt(hex.substring(3, 5), 16);
  1696. var b = parseInt(hex.substring(5, 7), 16);
  1697. return Color3.FromInts(r, g, b);
  1698. };
  1699. /**
  1700. * Creates a new Vector3 from the starting index of the given array
  1701. * @param array defines the source array
  1702. * @param offset defines an offset in the source array
  1703. * @returns a new Color3 object
  1704. */
  1705. Color3.FromArray = function (array, offset) {
  1706. if (offset === void 0) { offset = 0; }
  1707. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1708. };
  1709. /**
  1710. * Creates a new Color3 from integer values (< 256)
  1711. * @param r defines the red component to read from (value between 0 and 255)
  1712. * @param g defines the green component to read from (value between 0 and 255)
  1713. * @param b defines the blue component to read from (value between 0 and 255)
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromInts = function (r, g, b) {
  1717. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1718. };
  1719. /**
  1720. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1721. * @param start defines the start Color3 value
  1722. * @param end defines the end Color3 value
  1723. * @param amount defines the gradient value between start and end
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Lerp = function (start, end, amount) {
  1727. var r = start.r + ((end.r - start.r) * amount);
  1728. var g = start.g + ((end.g - start.g) * amount);
  1729. var b = start.b + ((end.b - start.b) * amount);
  1730. return new Color3(r, g, b);
  1731. };
  1732. /**
  1733. * Returns a Color3 value containing a red color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Red = function () { return new Color3(1, 0, 0); };
  1737. /**
  1738. * Returns a Color3 value containing a green color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Green = function () { return new Color3(0, 1, 0); };
  1742. /**
  1743. * Returns a Color3 value containing a blue color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a black color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Black = function () { return new Color3(0, 0, 0); };
  1752. /**
  1753. * Returns a Color3 value containing a white color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.White = function () { return new Color3(1, 1, 1); };
  1757. /**
  1758. * Returns a Color3 value containing a purple color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1762. /**
  1763. * Returns a Color3 value containing a magenta color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a yellow color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a gray color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1777. /**
  1778. * Returns a Color3 value containing a teal color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1782. /**
  1783. * Returns a Color3 value containing a random color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1787. return Color3;
  1788. }());
  1789. BABYLON.Color3 = Color3;
  1790. /**
  1791. * Class used to hold a RBGA color
  1792. */
  1793. var Color4 = /** @class */ (function () {
  1794. /**
  1795. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1796. * @param r defines the red component (between 0 and 1, default is 0)
  1797. * @param g defines the green component (between 0 and 1, default is 0)
  1798. * @param b defines the blue component (between 0 and 1, default is 0)
  1799. * @param a defines the alpha component (between 0 and 1, default is 1)
  1800. */
  1801. function Color4(
  1802. /**
  1803. * Defines the red component (between 0 and 1, default is 0)
  1804. */
  1805. r,
  1806. /**
  1807. * Defines the green component (between 0 and 1, default is 0)
  1808. */
  1809. g,
  1810. /**
  1811. * Defines the blue component (between 0 and 1, default is 0)
  1812. */
  1813. b,
  1814. /**
  1815. * Defines the alpha component (between 0 and 1, default is 1)
  1816. */
  1817. a) {
  1818. if (r === void 0) { r = 0; }
  1819. if (g === void 0) { g = 0; }
  1820. if (b === void 0) { b = 0; }
  1821. if (a === void 0) { a = 1; }
  1822. this.r = r;
  1823. this.g = g;
  1824. this.b = b;
  1825. this.a = a;
  1826. }
  1827. // Operators
  1828. /**
  1829. * Adds in place the given Color4 values to the current Color4 object
  1830. * @param right defines the second operand
  1831. * @returns the current updated Color4 object
  1832. */
  1833. Color4.prototype.addInPlace = function (right) {
  1834. this.r += right.r;
  1835. this.g += right.g;
  1836. this.b += right.b;
  1837. this.a += right.a;
  1838. return this;
  1839. };
  1840. /**
  1841. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1842. * @returns the new array
  1843. */
  1844. Color4.prototype.asArray = function () {
  1845. var result = new Array();
  1846. this.toArray(result, 0);
  1847. return result;
  1848. };
  1849. /**
  1850. * Stores from the starting index in the given array the Color4 successive values
  1851. * @param array defines the array where to store the r,g,b components
  1852. * @param index defines an optional index in the target array to define where to start storing values
  1853. * @returns the current Color4 object
  1854. */
  1855. Color4.prototype.toArray = function (array, index) {
  1856. if (index === undefined) {
  1857. index = 0;
  1858. }
  1859. array[index] = this.r;
  1860. array[index + 1] = this.g;
  1861. array[index + 2] = this.b;
  1862. array[index + 3] = this.a;
  1863. return this;
  1864. };
  1865. /**
  1866. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1867. * @param right defines the second operand
  1868. * @returns a new Color4 object
  1869. */
  1870. Color4.prototype.add = function (right) {
  1871. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1872. };
  1873. /**
  1874. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1875. * @param right defines the second operand
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.subtract = function (right) {
  1879. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1880. };
  1881. /**
  1882. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1883. * @param right defines the second operand
  1884. * @param result defines the Color4 object where to store the result
  1885. * @returns the current Color4 object
  1886. */
  1887. Color4.prototype.subtractToRef = function (right, result) {
  1888. result.r = this.r - right.r;
  1889. result.g = this.g - right.g;
  1890. result.b = this.b - right.b;
  1891. result.a = this.a - right.a;
  1892. return this;
  1893. };
  1894. /**
  1895. * Creates a new Color4 with the current Color4 values multiplied by scale
  1896. * @param scale defines the scaling factor to apply
  1897. * @returns a new Color4 object
  1898. */
  1899. Color4.prototype.scale = function (scale) {
  1900. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1901. };
  1902. /**
  1903. * Multiplies the current Color4 values by scale and stores the result in "result"
  1904. * @param scale defines the scaling factor to apply
  1905. * @param result defines the Color4 object where to store the result
  1906. * @returns the current unmodified Color4
  1907. */
  1908. Color4.prototype.scaleToRef = function (scale, result) {
  1909. result.r = this.r * scale;
  1910. result.g = this.g * scale;
  1911. result.b = this.b * scale;
  1912. result.a = this.a * scale;
  1913. return this;
  1914. };
  1915. /**
  1916. * Scale the current Color4 values by a factor and add the result to a given Color4
  1917. * @param scale defines the scale factor
  1918. * @param result defines the Color4 object where to store the result
  1919. * @returns the unmodified current Color4
  1920. */
  1921. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1922. result.r += this.r * scale;
  1923. result.g += this.g * scale;
  1924. result.b += this.b * scale;
  1925. result.a += this.a * scale;
  1926. return this;
  1927. };
  1928. /**
  1929. * Clamps the rgb values by the min and max values and stores the result into "result"
  1930. * @param min defines minimum clamping value (default is 0)
  1931. * @param max defines maximum clamping value (default is 1)
  1932. * @param result defines color to store the result into.
  1933. * @returns the cuurent Color4
  1934. */
  1935. Color4.prototype.clampToRef = function (min, max, result) {
  1936. if (min === void 0) { min = 0; }
  1937. if (max === void 0) { max = 1; }
  1938. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1939. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1940. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1941. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1942. return this;
  1943. };
  1944. /**
  1945. * Multipy an Color4 value by another and return a new Color4 object
  1946. * @param color defines the Color4 value to multiply by
  1947. * @returns a new Color4 object
  1948. */
  1949. Color4.prototype.multiply = function (color) {
  1950. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1951. };
  1952. /**
  1953. * Multipy a Color4 value by another and push the result in a reference value
  1954. * @param color defines the Color4 value to multiply by
  1955. * @param result defines the Color4 to fill the result in
  1956. * @returns the result Color4
  1957. */
  1958. Color4.prototype.multiplyToRef = function (color, result) {
  1959. result.r = this.r * color.r;
  1960. result.g = this.g * color.g;
  1961. result.b = this.b * color.b;
  1962. result.a = this.a * color.a;
  1963. return result;
  1964. };
  1965. /**
  1966. * Creates a string with the Color4 current values
  1967. * @returns the string representation of the Color4 object
  1968. */
  1969. Color4.prototype.toString = function () {
  1970. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1971. };
  1972. /**
  1973. * Returns the string "Color4"
  1974. * @returns "Color4"
  1975. */
  1976. Color4.prototype.getClassName = function () {
  1977. return "Color4";
  1978. };
  1979. /**
  1980. * Compute the Color4 hash code
  1981. * @returns an unique number that can be used to hash Color4 objects
  1982. */
  1983. Color4.prototype.getHashCode = function () {
  1984. var hash = this.r || 0;
  1985. hash = (hash * 397) ^ (this.g || 0);
  1986. hash = (hash * 397) ^ (this.b || 0);
  1987. hash = (hash * 397) ^ (this.a || 0);
  1988. return hash;
  1989. };
  1990. /**
  1991. * Creates a new Color4 copied from the current one
  1992. * @returns a new Color4 object
  1993. */
  1994. Color4.prototype.clone = function () {
  1995. return new Color4(this.r, this.g, this.b, this.a);
  1996. };
  1997. /**
  1998. * Copies the given Color4 values into the current one
  1999. * @param source defines the source Color4 object
  2000. * @returns the current updated Color4 object
  2001. */
  2002. Color4.prototype.copyFrom = function (source) {
  2003. this.r = source.r;
  2004. this.g = source.g;
  2005. this.b = source.b;
  2006. this.a = source.a;
  2007. return this;
  2008. };
  2009. /**
  2010. * Copies the given float values into the current one
  2011. * @param r defines the red component to read from
  2012. * @param g defines the green component to read from
  2013. * @param b defines the blue component to read from
  2014. * @param a defines the alpha component to read from
  2015. * @returns the current updated Color4 object
  2016. */
  2017. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2018. this.r = r;
  2019. this.g = g;
  2020. this.b = b;
  2021. this.a = a;
  2022. return this;
  2023. };
  2024. /**
  2025. * Copies the given float values into the current one
  2026. * @param r defines the red component to read from
  2027. * @param g defines the green component to read from
  2028. * @param b defines the blue component to read from
  2029. * @param a defines the alpha component to read from
  2030. * @returns the current updated Color4 object
  2031. */
  2032. Color4.prototype.set = function (r, g, b, a) {
  2033. return this.copyFromFloats(r, g, b, a);
  2034. };
  2035. /**
  2036. * Compute the Color4 hexadecimal code as a string
  2037. * @returns a string containing the hexadecimal representation of the Color4 object
  2038. */
  2039. Color4.prototype.toHexString = function () {
  2040. var intR = (this.r * 255) | 0;
  2041. var intG = (this.g * 255) | 0;
  2042. var intB = (this.b * 255) | 0;
  2043. var intA = (this.a * 255) | 0;
  2044. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2045. };
  2046. /**
  2047. * Computes a new Color4 converted from the current one to linear space
  2048. * @returns a new Color4 object
  2049. */
  2050. Color4.prototype.toLinearSpace = function () {
  2051. var convertedColor = new Color4();
  2052. this.toLinearSpaceToRef(convertedColor);
  2053. return convertedColor;
  2054. };
  2055. /**
  2056. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2057. * @param convertedColor defines the Color4 object where to store the linear space version
  2058. * @returns the unmodified Color4
  2059. */
  2060. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2061. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2062. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2063. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2064. convertedColor.a = this.a;
  2065. return this;
  2066. };
  2067. /**
  2068. * Computes a new Color4 converted from the current one to gamma space
  2069. * @returns a new Color4 object
  2070. */
  2071. Color4.prototype.toGammaSpace = function () {
  2072. var convertedColor = new Color4();
  2073. this.toGammaSpaceToRef(convertedColor);
  2074. return convertedColor;
  2075. };
  2076. /**
  2077. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2078. * @param convertedColor defines the Color4 object where to store the gamma space version
  2079. * @returns the unmodified Color4
  2080. */
  2081. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2082. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2083. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2084. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2085. convertedColor.a = this.a;
  2086. return this;
  2087. };
  2088. // Statics
  2089. /**
  2090. * Creates a new Color4 from the string containing valid hexadecimal values
  2091. * @param hex defines a string containing valid hexadecimal values
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.FromHexString = function (hex) {
  2095. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2096. return new Color4(0.0, 0.0, 0.0, 0.0);
  2097. }
  2098. var r = parseInt(hex.substring(1, 3), 16);
  2099. var g = parseInt(hex.substring(3, 5), 16);
  2100. var b = parseInt(hex.substring(5, 7), 16);
  2101. var a = parseInt(hex.substring(7, 9), 16);
  2102. return Color4.FromInts(r, g, b, a);
  2103. };
  2104. /**
  2105. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2106. * @param left defines the start value
  2107. * @param right defines the end value
  2108. * @param amount defines the gradient factor
  2109. * @returns a new Color4 object
  2110. */
  2111. Color4.Lerp = function (left, right, amount) {
  2112. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2113. Color4.LerpToRef(left, right, amount, result);
  2114. return result;
  2115. };
  2116. /**
  2117. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2118. * @param left defines the start value
  2119. * @param right defines the end value
  2120. * @param amount defines the gradient factor
  2121. * @param result defines the Color4 object where to store data
  2122. */
  2123. Color4.LerpToRef = function (left, right, amount, result) {
  2124. result.r = left.r + (right.r - left.r) * amount;
  2125. result.g = left.g + (right.g - left.g) * amount;
  2126. result.b = left.b + (right.b - left.b) * amount;
  2127. result.a = left.a + (right.a - left.a) * amount;
  2128. };
  2129. /**
  2130. * Creates a new Color4 from the starting index element of the given array
  2131. * @param array defines the source array to read from
  2132. * @param offset defines the offset in the source array
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.FromArray = function (array, offset) {
  2136. if (offset === void 0) { offset = 0; }
  2137. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2138. };
  2139. /**
  2140. * Creates a new Color3 from integer values (< 256)
  2141. * @param r defines the red component to read from (value between 0 and 255)
  2142. * @param g defines the green component to read from (value between 0 and 255)
  2143. * @param b defines the blue component to read from (value between 0 and 255)
  2144. * @param a defines the alpha component to read from (value between 0 and 255)
  2145. * @returns a new Color3 object
  2146. */
  2147. Color4.FromInts = function (r, g, b, a) {
  2148. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2149. };
  2150. /**
  2151. * Check the content of a given array and convert it to an array containing RGBA data
  2152. * If the original array was already containing count * 4 values then it is returned directly
  2153. * @param colors defines the array to check
  2154. * @param count defines the number of RGBA data to expect
  2155. * @returns an array containing count * 4 values (RGBA)
  2156. */
  2157. Color4.CheckColors4 = function (colors, count) {
  2158. // Check if color3 was used
  2159. if (colors.length === count * 3) {
  2160. var colors4 = [];
  2161. for (var index = 0; index < colors.length; index += 3) {
  2162. var newIndex = (index / 3) * 4;
  2163. colors4[newIndex] = colors[index];
  2164. colors4[newIndex + 1] = colors[index + 1];
  2165. colors4[newIndex + 2] = colors[index + 2];
  2166. colors4[newIndex + 3] = 1.0;
  2167. }
  2168. return colors4;
  2169. }
  2170. return colors;
  2171. };
  2172. return Color4;
  2173. }());
  2174. BABYLON.Color4 = Color4;
  2175. /**
  2176. * Class representing a vector containing 2 coordinates
  2177. */
  2178. var Vector2 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector2 from the given x and y coordinates
  2181. * @param x defines the first coordinate
  2182. * @param y defines the second coordinate
  2183. */
  2184. function Vector2(
  2185. /** defines the first coordinate */
  2186. x,
  2187. /** defines the second coordinate */
  2188. y) {
  2189. if (x === void 0) { x = 0; }
  2190. if (y === void 0) { y = 0; }
  2191. this.x = x;
  2192. this.y = y;
  2193. }
  2194. /**
  2195. * Gets a string with the Vector2 coordinates
  2196. * @returns a string with the Vector2 coordinates
  2197. */
  2198. Vector2.prototype.toString = function () {
  2199. return "{X: " + this.x + " Y:" + this.y + "}";
  2200. };
  2201. /**
  2202. * Gets class name
  2203. * @returns the string "Vector2"
  2204. */
  2205. Vector2.prototype.getClassName = function () {
  2206. return "Vector2";
  2207. };
  2208. /**
  2209. * Gets current vector hash code
  2210. * @returns the Vector2 hash code as a number
  2211. */
  2212. Vector2.prototype.getHashCode = function () {
  2213. var hash = this.x || 0;
  2214. hash = (hash * 397) ^ (this.y || 0);
  2215. return hash;
  2216. };
  2217. // Operators
  2218. /**
  2219. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2220. * @param array defines the source array
  2221. * @param index defines the offset in source array
  2222. * @returns the current Vector2
  2223. */
  2224. Vector2.prototype.toArray = function (array, index) {
  2225. if (index === void 0) { index = 0; }
  2226. array[index] = this.x;
  2227. array[index + 1] = this.y;
  2228. return this;
  2229. };
  2230. /**
  2231. * Copy the current vector to an array
  2232. * @returns a new array with 2 elements: the Vector2 coordinates.
  2233. */
  2234. Vector2.prototype.asArray = function () {
  2235. var result = new Array();
  2236. this.toArray(result, 0);
  2237. return result;
  2238. };
  2239. /**
  2240. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2241. * @param source defines the source Vector2
  2242. * @returns the current updated Vector2
  2243. */
  2244. Vector2.prototype.copyFrom = function (source) {
  2245. this.x = source.x;
  2246. this.y = source.y;
  2247. return this;
  2248. };
  2249. /**
  2250. * Sets the Vector2 coordinates with the given floats
  2251. * @param x defines the first coordinate
  2252. * @param y defines the second coordinate
  2253. * @returns the current updated Vector2
  2254. */
  2255. Vector2.prototype.copyFromFloats = function (x, y) {
  2256. this.x = x;
  2257. this.y = y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the given floats
  2262. * @param x defines the first coordinate
  2263. * @param y defines the second coordinate
  2264. * @returns the current updated Vector2
  2265. */
  2266. Vector2.prototype.set = function (x, y) {
  2267. return this.copyFromFloats(x, y);
  2268. };
  2269. /**
  2270. * Add another vector with the current one
  2271. * @param otherVector defines the other vector
  2272. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2273. */
  2274. Vector2.prototype.add = function (otherVector) {
  2275. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2276. };
  2277. /**
  2278. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2279. * @param otherVector defines the other vector
  2280. * @param result defines the target vector
  2281. * @returns the unmodified current Vector2
  2282. */
  2283. Vector2.prototype.addToRef = function (otherVector, result) {
  2284. result.x = this.x + otherVector.x;
  2285. result.y = this.y + otherVector.y;
  2286. return this;
  2287. };
  2288. /**
  2289. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2290. * @param otherVector defines the other vector
  2291. * @returns the current updated Vector2
  2292. */
  2293. Vector2.prototype.addInPlace = function (otherVector) {
  2294. this.x += otherVector.x;
  2295. this.y += otherVector.y;
  2296. return this;
  2297. };
  2298. /**
  2299. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2300. * @param otherVector defines the other vector
  2301. * @returns a new Vector2
  2302. */
  2303. Vector2.prototype.addVector3 = function (otherVector) {
  2304. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2305. };
  2306. /**
  2307. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2308. * @param otherVector defines the other vector
  2309. * @returns a new Vector2
  2310. */
  2311. Vector2.prototype.subtract = function (otherVector) {
  2312. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2313. };
  2314. /**
  2315. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2316. * @param otherVector defines the other vector
  2317. * @param result defines the target vector
  2318. * @returns the unmodified current Vector2
  2319. */
  2320. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2321. result.x = this.x - otherVector.x;
  2322. result.y = this.y - otherVector.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2327. * @param otherVector defines the other vector
  2328. * @returns the current updated Vector2
  2329. */
  2330. Vector2.prototype.subtractInPlace = function (otherVector) {
  2331. this.x -= otherVector.x;
  2332. this.y -= otherVector.y;
  2333. return this;
  2334. };
  2335. /**
  2336. * Multiplies in place the current Vector2 coordinates by the given ones
  2337. * @param otherVector defines the other vector
  2338. * @returns the current updated Vector2
  2339. */
  2340. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2341. this.x *= otherVector.x;
  2342. this.y *= otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2347. * @param otherVector defines the other vector
  2348. * @returns a new Vector2
  2349. */
  2350. Vector2.prototype.multiply = function (otherVector) {
  2351. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2352. };
  2353. /**
  2354. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2355. * @param otherVector defines the other vector
  2356. * @param result defines the target vector
  2357. * @returns the unmodified current Vector2
  2358. */
  2359. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2360. result.x = this.x * otherVector.x;
  2361. result.y = this.y * otherVector.y;
  2362. return this;
  2363. };
  2364. /**
  2365. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2366. * @param x defines the first coordinate
  2367. * @param y defines the second coordinate
  2368. * @returns a new Vector2
  2369. */
  2370. Vector2.prototype.multiplyByFloats = function (x, y) {
  2371. return new Vector2(this.x * x, this.y * y);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2375. * @param otherVector defines the other vector
  2376. * @returns a new Vector2
  2377. */
  2378. Vector2.prototype.divide = function (otherVector) {
  2379. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2380. };
  2381. /**
  2382. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2383. * @param otherVector defines the other vector
  2384. * @param result defines the target vector
  2385. * @returns the unmodified current Vector2
  2386. */
  2387. Vector2.prototype.divideToRef = function (otherVector, result) {
  2388. result.x = this.x / otherVector.x;
  2389. result.y = this.y / otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Divides the current Vector3 coordinates by the given ones
  2394. * @param otherVector defines the other vector
  2395. * @returns the current updated Vector2
  2396. */
  2397. Vector2.prototype.divideInPlace = function (otherVector) {
  2398. return this.divideToRef(otherVector, this);
  2399. };
  2400. /**
  2401. * Gets a new Vector2 with current Vector2 negated coordinates
  2402. * @returns a new Vector2
  2403. */
  2404. Vector2.prototype.negate = function () {
  2405. return new Vector2(-this.x, -this.y);
  2406. };
  2407. /**
  2408. * Multiply the Vector2 coordinates by scale
  2409. * @param scale defines the scaling factor
  2410. * @returns the current updated Vector2
  2411. */
  2412. Vector2.prototype.scaleInPlace = function (scale) {
  2413. this.x *= scale;
  2414. this.y *= scale;
  2415. return this;
  2416. };
  2417. /**
  2418. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2419. * @param scale defines the scaling factor
  2420. * @returns a new Vector2
  2421. */
  2422. Vector2.prototype.scale = function (scale) {
  2423. var result = new Vector2(0, 0);
  2424. this.scaleToRef(scale, result);
  2425. return result;
  2426. };
  2427. /**
  2428. * Scale the current Vector2 values by a factor to a given Vector2
  2429. * @param scale defines the scale factor
  2430. * @param result defines the Vector2 object where to store the result
  2431. * @returns the unmodified current Vector2
  2432. */
  2433. Vector2.prototype.scaleToRef = function (scale, result) {
  2434. result.x = this.x * scale;
  2435. result.y = this.y * scale;
  2436. return this;
  2437. };
  2438. /**
  2439. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2440. * @param scale defines the scale factor
  2441. * @param result defines the Vector2 object where to store the result
  2442. * @returns the unmodified current Vector2
  2443. */
  2444. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2445. result.x += this.x * scale;
  2446. result.y += this.y * scale;
  2447. return this;
  2448. };
  2449. /**
  2450. * Gets a boolean if two vectors are equals
  2451. * @param otherVector defines the other vector
  2452. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2453. */
  2454. Vector2.prototype.equals = function (otherVector) {
  2455. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2456. };
  2457. /**
  2458. * Gets a boolean if two vectors are equals (using an epsilon value)
  2459. * @param otherVector defines the other vector
  2460. * @param epsilon defines the minimal distance to consider equality
  2461. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2462. */
  2463. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2464. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2465. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2466. };
  2467. // Properties
  2468. /**
  2469. * Gets the length of the vector
  2470. * @returns the vector length (float)
  2471. */
  2472. Vector2.prototype.length = function () {
  2473. return Math.sqrt(this.x * this.x + this.y * this.y);
  2474. };
  2475. /**
  2476. * Gets the vector squared length
  2477. * @returns the vector squared length (float)
  2478. */
  2479. Vector2.prototype.lengthSquared = function () {
  2480. return (this.x * this.x + this.y * this.y);
  2481. };
  2482. // Methods
  2483. /**
  2484. * Normalize the vector
  2485. * @returns the current updated Vector2
  2486. */
  2487. Vector2.prototype.normalize = function () {
  2488. var len = this.length();
  2489. if (len === 0)
  2490. return this;
  2491. var num = 1.0 / len;
  2492. this.x *= num;
  2493. this.y *= num;
  2494. return this;
  2495. };
  2496. /**
  2497. * Gets a new Vector2 copied from the Vector2
  2498. * @returns a new Vector2
  2499. */
  2500. Vector2.prototype.clone = function () {
  2501. return new Vector2(this.x, this.y);
  2502. };
  2503. // Statics
  2504. /**
  2505. * Gets a new Vector2(0, 0)
  2506. * @returns a new Vector2
  2507. */
  2508. Vector2.Zero = function () {
  2509. return new Vector2(0, 0);
  2510. };
  2511. /**
  2512. * Gets a new Vector2(1, 1)
  2513. * @returns a new Vector2
  2514. */
  2515. Vector2.One = function () {
  2516. return new Vector2(1, 1);
  2517. };
  2518. /**
  2519. * Gets a new Vector2 set from the given index element of the given array
  2520. * @param array defines the data source
  2521. * @param offset defines the offset in the data source
  2522. * @returns a new Vector2
  2523. */
  2524. Vector2.FromArray = function (array, offset) {
  2525. if (offset === void 0) { offset = 0; }
  2526. return new Vector2(array[offset], array[offset + 1]);
  2527. };
  2528. /**
  2529. * Sets "result" from the given index element of the given array
  2530. * @param array defines the data source
  2531. * @param offset defines the offset in the data source
  2532. * @param result defines the target vector
  2533. */
  2534. Vector2.FromArrayToRef = function (array, offset, result) {
  2535. result.x = array[offset];
  2536. result.y = array[offset + 1];
  2537. };
  2538. /**
  2539. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2540. * @param value1 defines 1st point of control
  2541. * @param value2 defines 2nd point of control
  2542. * @param value3 defines 3rd point of control
  2543. * @param value4 defines 4th point of control
  2544. * @param amount defines the interpolation factor
  2545. * @returns a new Vector2
  2546. */
  2547. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2548. var squared = amount * amount;
  2549. var cubed = amount * squared;
  2550. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2551. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2552. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2553. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2554. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2555. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2556. return new Vector2(x, y);
  2557. };
  2558. /**
  2559. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2560. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2561. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2562. * @param value defines the value to clamp
  2563. * @param min defines the lower limit
  2564. * @param max defines the upper limit
  2565. * @returns a new Vector2
  2566. */
  2567. Vector2.Clamp = function (value, min, max) {
  2568. var x = value.x;
  2569. x = (x > max.x) ? max.x : x;
  2570. x = (x < min.x) ? min.x : x;
  2571. var y = value.y;
  2572. y = (y > max.y) ? max.y : y;
  2573. y = (y < min.y) ? min.y : y;
  2574. return new Vector2(x, y);
  2575. };
  2576. /**
  2577. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2578. * @param value1 defines the 1st control point
  2579. * @param tangent1 defines the outgoing tangent
  2580. * @param value2 defines the 2nd control point
  2581. * @param tangent2 defines the incoming tangent
  2582. * @param amount defines the interpolation factor
  2583. * @returns a new Vector2
  2584. */
  2585. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2586. var squared = amount * amount;
  2587. var cubed = amount * squared;
  2588. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2589. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2590. var part3 = (cubed - (2.0 * squared)) + amount;
  2591. var part4 = cubed - squared;
  2592. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2593. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2594. return new Vector2(x, y);
  2595. };
  2596. /**
  2597. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2598. * @param start defines the start vector
  2599. * @param end defines the end vector
  2600. * @param amount defines the interpolation factor
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.Lerp = function (start, end, amount) {
  2604. var x = start.x + ((end.x - start.x) * amount);
  2605. var y = start.y + ((end.y - start.y) * amount);
  2606. return new Vector2(x, y);
  2607. };
  2608. /**
  2609. * Gets the dot product of the vector "left" and the vector "right"
  2610. * @param left defines first vector
  2611. * @param right defines second vector
  2612. * @returns the dot product (float)
  2613. */
  2614. Vector2.Dot = function (left, right) {
  2615. return left.x * right.x + left.y * right.y;
  2616. };
  2617. /**
  2618. * Returns a new Vector2 equal to the normalized given vector
  2619. * @param vector defines the vector to normalize
  2620. * @returns a new Vector2
  2621. */
  2622. Vector2.Normalize = function (vector) {
  2623. var newVector = vector.clone();
  2624. newVector.normalize();
  2625. return newVector;
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2629. * @param left defines 1st vector
  2630. * @param right defines 2nd vector
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.Minimize = function (left, right) {
  2634. var x = (left.x < right.x) ? left.x : right.x;
  2635. var y = (left.y < right.y) ? left.y : right.y;
  2636. return new Vector2(x, y);
  2637. };
  2638. /**
  2639. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2640. * @param left defines 1st vector
  2641. * @param right defines 2nd vector
  2642. * @returns a new Vector2
  2643. */
  2644. Vector2.Maximize = function (left, right) {
  2645. var x = (left.x > right.x) ? left.x : right.x;
  2646. var y = (left.y > right.y) ? left.y : right.y;
  2647. return new Vector2(x, y);
  2648. };
  2649. /**
  2650. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2651. * @param vector defines the vector to transform
  2652. * @param transformation defines the matrix to apply
  2653. * @returns a new Vector2
  2654. */
  2655. Vector2.Transform = function (vector, transformation) {
  2656. var r = Vector2.Zero();
  2657. Vector2.TransformToRef(vector, transformation, r);
  2658. return r;
  2659. };
  2660. /**
  2661. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2662. * @param vector defines the vector to transform
  2663. * @param transformation defines the matrix to apply
  2664. * @param result defines the target vector
  2665. */
  2666. Vector2.TransformToRef = function (vector, transformation, result) {
  2667. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2668. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2669. result.x = x;
  2670. result.y = y;
  2671. };
  2672. /**
  2673. * Determines if a given vector is included in a triangle
  2674. * @param p defines the vector to test
  2675. * @param p0 defines 1st triangle point
  2676. * @param p1 defines 2nd triangle point
  2677. * @param p2 defines 3rd triangle point
  2678. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2679. */
  2680. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2681. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2682. var sign = a < 0 ? -1 : 1;
  2683. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2684. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2685. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2686. };
  2687. /**
  2688. * Gets the distance between the vectors "value1" and "value2"
  2689. * @param value1 defines first vector
  2690. * @param value2 defines second vector
  2691. * @returns the distance between vectors
  2692. */
  2693. Vector2.Distance = function (value1, value2) {
  2694. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2695. };
  2696. /**
  2697. * Returns the squared distance between the vectors "value1" and "value2"
  2698. * @param value1 defines first vector
  2699. * @param value2 defines second vector
  2700. * @returns the squared distance between vectors
  2701. */
  2702. Vector2.DistanceSquared = function (value1, value2) {
  2703. var x = value1.x - value2.x;
  2704. var y = value1.y - value2.y;
  2705. return (x * x) + (y * y);
  2706. };
  2707. /**
  2708. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2709. * @param value1 defines first vector
  2710. * @param value2 defines second vector
  2711. * @returns a new Vector2
  2712. */
  2713. Vector2.Center = function (value1, value2) {
  2714. var center = value1.add(value2);
  2715. center.scaleInPlace(0.5);
  2716. return center;
  2717. };
  2718. /**
  2719. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2720. * @param p defines the middle point
  2721. * @param segA defines one point of the segment
  2722. * @param segB defines the other point of the segment
  2723. * @returns the shortest distance
  2724. */
  2725. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2726. var l2 = Vector2.DistanceSquared(segA, segB);
  2727. if (l2 === 0.0) {
  2728. return Vector2.Distance(p, segA);
  2729. }
  2730. var v = segB.subtract(segA);
  2731. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2732. var proj = segA.add(v.multiplyByFloats(t, t));
  2733. return Vector2.Distance(p, proj);
  2734. };
  2735. return Vector2;
  2736. }());
  2737. BABYLON.Vector2 = Vector2;
  2738. /**
  2739. * Classed used to store (x,y,z) vector representation
  2740. * A Vector3 is the main object used in 3D geometry
  2741. * It can represent etiher the coordinates of a point the space, either a direction
  2742. * Reminder: Babylon.js uses a left handed forward facing system
  2743. */
  2744. var Vector3 = /** @class */ (function () {
  2745. /**
  2746. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2747. * @param x defines the first coordinates (on X axis)
  2748. * @param y defines the second coordinates (on Y axis)
  2749. * @param z defines the third coordinates (on Z axis)
  2750. */
  2751. function Vector3(
  2752. /**
  2753. * Defines the first coordinates (on X axis)
  2754. */
  2755. x,
  2756. /**
  2757. * Defines the second coordinates (on Y axis)
  2758. */
  2759. y,
  2760. /**
  2761. * Defines the third coordinates (on Z axis)
  2762. */
  2763. z) {
  2764. if (x === void 0) { x = 0; }
  2765. if (y === void 0) { y = 0; }
  2766. if (z === void 0) { z = 0; }
  2767. this.x = x;
  2768. this.y = y;
  2769. this.z = z;
  2770. }
  2771. /**
  2772. * Creates a string representation of the Vector3
  2773. * @returns a string with the Vector3 coordinates.
  2774. */
  2775. Vector3.prototype.toString = function () {
  2776. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2777. };
  2778. /**
  2779. * Gets the class name
  2780. * @returns the string "Vector3"
  2781. */
  2782. Vector3.prototype.getClassName = function () {
  2783. return "Vector3";
  2784. };
  2785. /**
  2786. * Creates the Vector3 hash code
  2787. * @returns a number which tends to be unique between Vector3 instances
  2788. */
  2789. Vector3.prototype.getHashCode = function () {
  2790. var hash = this.x || 0;
  2791. hash = (hash * 397) ^ (this.y || 0);
  2792. hash = (hash * 397) ^ (this.z || 0);
  2793. return hash;
  2794. };
  2795. // Operators
  2796. /**
  2797. * Creates an array containing three elements : the coordinates of the Vector3
  2798. * @returns a new array of numbers
  2799. */
  2800. Vector3.prototype.asArray = function () {
  2801. var result = [];
  2802. this.toArray(result, 0);
  2803. return result;
  2804. };
  2805. /**
  2806. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2807. * @param array defines the destination array
  2808. * @param index defines the offset in the destination array
  2809. * @returns the current Vector3
  2810. */
  2811. Vector3.prototype.toArray = function (array, index) {
  2812. if (index === void 0) { index = 0; }
  2813. array[index] = this.x;
  2814. array[index + 1] = this.y;
  2815. array[index + 2] = this.z;
  2816. return this;
  2817. };
  2818. /**
  2819. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2820. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2821. */
  2822. Vector3.prototype.toQuaternion = function () {
  2823. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2824. };
  2825. /**
  2826. * Adds the given vector to the current Vector3
  2827. * @param otherVector defines the second operand
  2828. * @returns the current updated Vector3
  2829. */
  2830. Vector3.prototype.addInPlace = function (otherVector) {
  2831. this.x += otherVector.x;
  2832. this.y += otherVector.y;
  2833. this.z += otherVector.z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2838. * @param otherVector defines the second operand
  2839. * @returns the resulting Vector3
  2840. */
  2841. Vector3.prototype.add = function (otherVector) {
  2842. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2843. };
  2844. /**
  2845. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2846. * @param otherVector defines the second operand
  2847. * @param result defines the Vector3 object where to store the result
  2848. * @returns the current Vector3
  2849. */
  2850. Vector3.prototype.addToRef = function (otherVector, result) {
  2851. result.x = this.x + otherVector.x;
  2852. result.y = this.y + otherVector.y;
  2853. result.z = this.z + otherVector.z;
  2854. return this;
  2855. };
  2856. /**
  2857. * Subtract the given vector from the current Vector3
  2858. * @param otherVector defines the second operand
  2859. * @returns the current updated Vector3
  2860. */
  2861. Vector3.prototype.subtractInPlace = function (otherVector) {
  2862. this.x -= otherVector.x;
  2863. this.y -= otherVector.y;
  2864. this.z -= otherVector.z;
  2865. return this;
  2866. };
  2867. /**
  2868. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2869. * @param otherVector defines the second operand
  2870. * @returns the resulting Vector3
  2871. */
  2872. Vector3.prototype.subtract = function (otherVector) {
  2873. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2874. };
  2875. /**
  2876. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2877. * @param otherVector defines the second operand
  2878. * @param result defines the Vector3 object where to store the result
  2879. * @returns the current Vector3
  2880. */
  2881. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2882. result.x = this.x - otherVector.x;
  2883. result.y = this.y - otherVector.y;
  2884. result.z = this.z - otherVector.z;
  2885. return this;
  2886. };
  2887. /**
  2888. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2889. * @param x defines the x coordinate of the operand
  2890. * @param y defines the y coordinate of the operand
  2891. * @param z defines the z coordinate of the operand
  2892. * @returns the resulting Vector3
  2893. */
  2894. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2895. return new Vector3(this.x - x, this.y - y, this.z - z);
  2896. };
  2897. /**
  2898. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2899. * @param x defines the x coordinate of the operand
  2900. * @param y defines the y coordinate of the operand
  2901. * @param z defines the z coordinate of the operand
  2902. * @param result defines the Vector3 object where to store the result
  2903. * @returns the current Vector3
  2904. */
  2905. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2906. result.x = this.x - x;
  2907. result.y = this.y - y;
  2908. result.z = this.z - z;
  2909. return this;
  2910. };
  2911. /**
  2912. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2913. * @returns a new Vector3
  2914. */
  2915. Vector3.prototype.negate = function () {
  2916. return new Vector3(-this.x, -this.y, -this.z);
  2917. };
  2918. /**
  2919. * Multiplies the Vector3 coordinates by the float "scale"
  2920. * @param scale defines the multiplier factor
  2921. * @returns the current updated Vector3
  2922. */
  2923. Vector3.prototype.scaleInPlace = function (scale) {
  2924. this.x *= scale;
  2925. this.y *= scale;
  2926. this.z *= scale;
  2927. return this;
  2928. };
  2929. /**
  2930. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2931. * @param scale defines the multiplier factor
  2932. * @returns a new Vector3
  2933. */
  2934. Vector3.prototype.scale = function (scale) {
  2935. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2936. };
  2937. /**
  2938. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2939. * @param scale defines the multiplier factor
  2940. * @param result defines the Vector3 object where to store the result
  2941. * @returns the current Vector3
  2942. */
  2943. Vector3.prototype.scaleToRef = function (scale, result) {
  2944. result.x = this.x * scale;
  2945. result.y = this.y * scale;
  2946. result.z = this.z * scale;
  2947. return this;
  2948. };
  2949. /**
  2950. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2951. * @param scale defines the scale factor
  2952. * @param result defines the Vector3 object where to store the result
  2953. * @returns the unmodified current Vector3
  2954. */
  2955. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2956. result.x += this.x * scale;
  2957. result.y += this.y * scale;
  2958. result.z += this.z * scale;
  2959. return this;
  2960. };
  2961. /**
  2962. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2963. * @param otherVector defines the second operand
  2964. * @returns true if both vectors are equals
  2965. */
  2966. Vector3.prototype.equals = function (otherVector) {
  2967. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2968. };
  2969. /**
  2970. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2971. * @param otherVector defines the second operand
  2972. * @param epsilon defines the minimal distance to define values as equals
  2973. * @returns true if both vectors are distant less than epsilon
  2974. */
  2975. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2976. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2977. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2978. };
  2979. /**
  2980. * Returns true if the current Vector3 coordinates equals the given floats
  2981. * @param x defines the x coordinate of the operand
  2982. * @param y defines the y coordinate of the operand
  2983. * @param z defines the z coordinate of the operand
  2984. * @returns true if both vectors are equals
  2985. */
  2986. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2987. return this.x === x && this.y === y && this.z === z;
  2988. };
  2989. /**
  2990. * Multiplies the current Vector3 coordinates by the given ones
  2991. * @param otherVector defines the second operand
  2992. * @returns the current updated Vector3
  2993. */
  2994. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2995. this.x *= otherVector.x;
  2996. this.y *= otherVector.y;
  2997. this.z *= otherVector.z;
  2998. return this;
  2999. };
  3000. /**
  3001. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3002. * @param otherVector defines the second operand
  3003. * @returns the new Vector3
  3004. */
  3005. Vector3.prototype.multiply = function (otherVector) {
  3006. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3007. };
  3008. /**
  3009. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3010. * @param otherVector defines the second operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3015. result.x = this.x * otherVector.x;
  3016. result.y = this.y * otherVector.y;
  3017. result.z = this.z * otherVector.z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3022. * @param x defines the x coordinate of the operand
  3023. * @param y defines the y coordinate of the operand
  3024. * @param z defines the z coordinate of the operand
  3025. * @returns the new Vector3
  3026. */
  3027. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3028. return new Vector3(this.x * x, this.y * y, this.z * z);
  3029. };
  3030. /**
  3031. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3032. * @param otherVector defines the second operand
  3033. * @returns the new Vector3
  3034. */
  3035. Vector3.prototype.divide = function (otherVector) {
  3036. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3037. };
  3038. /**
  3039. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3040. * @param otherVector defines the second operand
  3041. * @param result defines the Vector3 object where to store the result
  3042. * @returns the current Vector3
  3043. */
  3044. Vector3.prototype.divideToRef = function (otherVector, result) {
  3045. result.x = this.x / otherVector.x;
  3046. result.y = this.y / otherVector.y;
  3047. result.z = this.z / otherVector.z;
  3048. return this;
  3049. };
  3050. /**
  3051. * Divides the current Vector3 coordinates by the given ones.
  3052. * @param otherVector defines the second operand
  3053. * @returns the current updated Vector3
  3054. */
  3055. Vector3.prototype.divideInPlace = function (otherVector) {
  3056. return this.divideToRef(otherVector, this);
  3057. };
  3058. /**
  3059. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3060. * @param other defines the second operand
  3061. * @returns the current updated Vector3
  3062. */
  3063. Vector3.prototype.minimizeInPlace = function (other) {
  3064. if (other.x < this.x)
  3065. this.x = other.x;
  3066. if (other.y < this.y)
  3067. this.y = other.y;
  3068. if (other.z < this.z)
  3069. this.z = other.z;
  3070. return this;
  3071. };
  3072. /**
  3073. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3074. * @param other defines the second operand
  3075. * @returns the current updated Vector3
  3076. */
  3077. Vector3.prototype.maximizeInPlace = function (other) {
  3078. if (other.x > this.x)
  3079. this.x = other.x;
  3080. if (other.y > this.y)
  3081. this.y = other.y;
  3082. if (other.z > this.z)
  3083. this.z = other.z;
  3084. return this;
  3085. };
  3086. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3087. /**
  3088. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3089. */
  3090. get: function () {
  3091. var absX = Math.abs(this.x);
  3092. var absY = Math.abs(this.y);
  3093. if (absX !== absY) {
  3094. return true;
  3095. }
  3096. var absZ = Math.abs(this.z);
  3097. if (absX !== absZ) {
  3098. return true;
  3099. }
  3100. if (absY !== absZ) {
  3101. return true;
  3102. }
  3103. return false;
  3104. },
  3105. enumerable: true,
  3106. configurable: true
  3107. });
  3108. // Properties
  3109. /**
  3110. * Gets the length of the Vector3
  3111. * @returns the length of the Vecto3
  3112. */
  3113. Vector3.prototype.length = function () {
  3114. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3115. };
  3116. /**
  3117. * Gets the squared length of the Vector3
  3118. * @returns squared length of the Vector3
  3119. */
  3120. Vector3.prototype.lengthSquared = function () {
  3121. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3122. };
  3123. /**
  3124. * Normalize the current Vector3.
  3125. * Please note that this is an in place operation.
  3126. * @returns the current updated Vector3
  3127. */
  3128. Vector3.prototype.normalize = function () {
  3129. var len = this.length();
  3130. if (len === 0 || len === 1.0)
  3131. return this;
  3132. var num = 1.0 / len;
  3133. this.x *= num;
  3134. this.y *= num;
  3135. this.z *= num;
  3136. return this;
  3137. };
  3138. /**
  3139. * Normalize the current Vector3 to a new vector
  3140. * @returns the new Vector3
  3141. */
  3142. Vector3.prototype.normalizeToNew = function () {
  3143. var normalized = new Vector3(0, 0, 0);
  3144. this.normalizeToRef(normalized);
  3145. return normalized;
  3146. };
  3147. /**
  3148. * Normalize the current Vector3 to the reference
  3149. * @param reference define the Vector3 to update
  3150. * @returns the updated Vector3
  3151. */
  3152. Vector3.prototype.normalizeToRef = function (reference) {
  3153. var len = this.length();
  3154. if (len === 0 || len === 1.0) {
  3155. reference.set(this.x, this.y, this.z);
  3156. return reference;
  3157. }
  3158. var scale = 1.0 / len;
  3159. this.scaleToRef(scale, reference);
  3160. return reference;
  3161. };
  3162. /**
  3163. * Creates a new Vector3 copied from the current Vector3
  3164. * @returns the new Vector3
  3165. */
  3166. Vector3.prototype.clone = function () {
  3167. return new Vector3(this.x, this.y, this.z);
  3168. };
  3169. /**
  3170. * Copies the given vector coordinates to the current Vector3 ones
  3171. * @param source defines the source Vector3
  3172. * @returns the current updated Vector3
  3173. */
  3174. Vector3.prototype.copyFrom = function (source) {
  3175. this.x = source.x;
  3176. this.y = source.y;
  3177. this.z = source.z;
  3178. return this;
  3179. };
  3180. /**
  3181. * Copies the given floats to the current Vector3 coordinates
  3182. * @param x defines the x coordinate of the operand
  3183. * @param y defines the y coordinate of the operand
  3184. * @param z defines the z coordinate of the operand
  3185. * @returns the current updated Vector3
  3186. */
  3187. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3188. this.x = x;
  3189. this.y = y;
  3190. this.z = z;
  3191. return this;
  3192. };
  3193. /**
  3194. * Copies the given floats to the current Vector3 coordinates
  3195. * @param x defines the x coordinate of the operand
  3196. * @param y defines the y coordinate of the operand
  3197. * @param z defines the z coordinate of the operand
  3198. * @returns the current updated Vector3
  3199. */
  3200. Vector3.prototype.set = function (x, y, z) {
  3201. return this.copyFromFloats(x, y, z);
  3202. };
  3203. // Statics
  3204. /**
  3205. * Get the clip factor between two vectors
  3206. * @param vector0 defines the first operand
  3207. * @param vector1 defines the second operand
  3208. * @param axis defines the axis to use
  3209. * @param size defines the size along the axis
  3210. * @returns the clip factor
  3211. */
  3212. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3213. var d0 = Vector3.Dot(vector0, axis) - size;
  3214. var d1 = Vector3.Dot(vector1, axis) - size;
  3215. var s = d0 / (d0 - d1);
  3216. return s;
  3217. };
  3218. /**
  3219. * Get angle between two vectors
  3220. * @param vector0 angle between vector0 and vector1
  3221. * @param vector1 angle between vector0 and vector1
  3222. * @param normal direction of the normal
  3223. * @return the angle between vector0 and vector1
  3224. */
  3225. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3226. var v0 = vector0.clone().normalize();
  3227. var v1 = vector1.clone().normalize();
  3228. var dot = Vector3.Dot(v0, v1);
  3229. var n = Vector3.Cross(v0, v1);
  3230. if (Vector3.Dot(n, normal) > 0) {
  3231. return Math.acos(dot);
  3232. }
  3233. return -Math.acos(dot);
  3234. };
  3235. /**
  3236. * Returns a new Vector3 set from the index "offset" of the given array
  3237. * @param array defines the source array
  3238. * @param offset defines the offset in the source array
  3239. * @returns the new Vector3
  3240. */
  3241. Vector3.FromArray = function (array, offset) {
  3242. if (!offset) {
  3243. offset = 0;
  3244. }
  3245. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3246. };
  3247. /**
  3248. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3249. * This function is deprecated. Use FromArray instead
  3250. * @param array defines the source array
  3251. * @param offset defines the offset in the source array
  3252. * @returns the new Vector3
  3253. */
  3254. Vector3.FromFloatArray = function (array, offset) {
  3255. return Vector3.FromArray(array, offset);
  3256. };
  3257. /**
  3258. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3259. * @param array defines the source array
  3260. * @param offset defines the offset in the source array
  3261. * @param result defines the Vector3 where to store the result
  3262. */
  3263. Vector3.FromArrayToRef = function (array, offset, result) {
  3264. result.x = array[offset];
  3265. result.y = array[offset + 1];
  3266. result.z = array[offset + 2];
  3267. };
  3268. /**
  3269. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3270. * This function is deprecated. Use FromArrayToRef instead.
  3271. * @param array defines the source array
  3272. * @param offset defines the offset in the source array
  3273. * @param result defines the Vector3 where to store the result
  3274. */
  3275. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3276. return Vector3.FromArrayToRef(array, offset, result);
  3277. };
  3278. /**
  3279. * Sets the given vector "result" with the given floats.
  3280. * @param x defines the x coordinate of the source
  3281. * @param y defines the y coordinate of the source
  3282. * @param z defines the z coordinate of the source
  3283. * @param result defines the Vector3 where to store the result
  3284. */
  3285. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3286. result.x = x;
  3287. result.y = y;
  3288. result.z = z;
  3289. };
  3290. /**
  3291. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3292. * @returns a new empty Vector3
  3293. */
  3294. Vector3.Zero = function () {
  3295. return new Vector3(0.0, 0.0, 0.0);
  3296. };
  3297. /**
  3298. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3299. * @returns a new unit Vector3
  3300. */
  3301. Vector3.One = function () {
  3302. return new Vector3(1.0, 1.0, 1.0);
  3303. };
  3304. /**
  3305. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3306. * @returns a new up Vector3
  3307. */
  3308. Vector3.Up = function () {
  3309. return new Vector3(0.0, 1.0, 0.0);
  3310. };
  3311. /**
  3312. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3313. * @returns a new down Vector3
  3314. */
  3315. Vector3.Down = function () {
  3316. return new Vector3(0.0, -1.0, 0.0);
  3317. };
  3318. /**
  3319. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3320. * @returns a new forward Vector3
  3321. */
  3322. Vector3.Forward = function () {
  3323. return new Vector3(0.0, 0.0, 1.0);
  3324. };
  3325. /**
  3326. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3327. * @returns a new right Vector3
  3328. */
  3329. Vector3.Right = function () {
  3330. return new Vector3(1.0, 0.0, 0.0);
  3331. };
  3332. /**
  3333. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3334. * @returns a new left Vector3
  3335. */
  3336. Vector3.Left = function () {
  3337. return new Vector3(-1.0, 0.0, 0.0);
  3338. };
  3339. /**
  3340. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3341. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3342. * @param vector defines the Vector3 to transform
  3343. * @param transformation defines the transformation matrix
  3344. * @returns the transformed Vector3
  3345. */
  3346. Vector3.TransformCoordinates = function (vector, transformation) {
  3347. var result = Vector3.Zero();
  3348. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3349. return result;
  3350. };
  3351. /**
  3352. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3353. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3354. * @param vector defines the Vector3 to transform
  3355. * @param transformation defines the transformation matrix
  3356. * @param result defines the Vector3 where to store the result
  3357. */
  3358. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3359. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3360. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3361. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3362. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3363. result.x = x / w;
  3364. result.y = y / w;
  3365. result.z = z / w;
  3366. };
  3367. /**
  3368. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3369. * This method computes tranformed coordinates only, not transformed direction vectors
  3370. * @param x define the x coordinate of the source vector
  3371. * @param y define the y coordinate of the source vector
  3372. * @param z define the z coordinate of the source vector
  3373. * @param transformation defines the transformation matrix
  3374. * @param result defines the Vector3 where to store the result
  3375. */
  3376. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3377. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3378. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3379. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3380. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3381. result.x = rx / rw;
  3382. result.y = ry / rw;
  3383. result.z = rz / rw;
  3384. };
  3385. /**
  3386. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3387. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3388. * @param vector defines the Vector3 to transform
  3389. * @param transformation defines the transformation matrix
  3390. * @returns the new Vector3
  3391. */
  3392. Vector3.TransformNormal = function (vector, transformation) {
  3393. var result = Vector3.Zero();
  3394. Vector3.TransformNormalToRef(vector, transformation, result);
  3395. return result;
  3396. };
  3397. /**
  3398. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3399. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3400. * @param vector defines the Vector3 to transform
  3401. * @param transformation defines the transformation matrix
  3402. * @param result defines the Vector3 where to store the result
  3403. */
  3404. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3405. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3406. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3407. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3408. result.x = x;
  3409. result.y = y;
  3410. result.z = z;
  3411. };
  3412. /**
  3413. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3414. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3415. * @param x define the x coordinate of the source vector
  3416. * @param y define the y coordinate of the source vector
  3417. * @param z define the z coordinate of the source vector
  3418. * @param transformation defines the transformation matrix
  3419. * @param result defines the Vector3 where to store the result
  3420. */
  3421. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3422. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3423. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3424. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3428. * @param value1 defines the first control point
  3429. * @param value2 defines the second control point
  3430. * @param value3 defines the third control point
  3431. * @param value4 defines the fourth control point
  3432. * @param amount defines the amount on the spline to use
  3433. * @returns the new Vector3
  3434. */
  3435. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3436. var squared = amount * amount;
  3437. var cubed = amount * squared;
  3438. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3439. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3440. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3441. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3442. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3443. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3444. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3445. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3446. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3447. return new Vector3(x, y, z);
  3448. };
  3449. /**
  3450. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3451. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3452. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3453. * @param value defines the current value
  3454. * @param min defines the lower range value
  3455. * @param max defines the upper range value
  3456. * @returns the new Vector3
  3457. */
  3458. Vector3.Clamp = function (value, min, max) {
  3459. var x = value.x;
  3460. x = (x > max.x) ? max.x : x;
  3461. x = (x < min.x) ? min.x : x;
  3462. var y = value.y;
  3463. y = (y > max.y) ? max.y : y;
  3464. y = (y < min.y) ? min.y : y;
  3465. var z = value.z;
  3466. z = (z > max.z) ? max.z : z;
  3467. z = (z < min.z) ? min.z : z;
  3468. return new Vector3(x, y, z);
  3469. };
  3470. /**
  3471. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3472. * @param value1 defines the first control point
  3473. * @param tangent1 defines the first tangent vector
  3474. * @param value2 defines the second control point
  3475. * @param tangent2 defines the second tangent vector
  3476. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3477. * @returns the new Vector3
  3478. */
  3479. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3480. var squared = amount * amount;
  3481. var cubed = amount * squared;
  3482. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3483. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3484. var part3 = (cubed - (2.0 * squared)) + amount;
  3485. var part4 = cubed - squared;
  3486. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3487. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3488. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3489. return new Vector3(x, y, z);
  3490. };
  3491. /**
  3492. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3493. * @param start defines the start value
  3494. * @param end defines the end value
  3495. * @param amount max defines amount between both (between 0 and 1)
  3496. * @returns the new Vector3
  3497. */
  3498. Vector3.Lerp = function (start, end, amount) {
  3499. var result = new Vector3(0, 0, 0);
  3500. Vector3.LerpToRef(start, end, amount, result);
  3501. return result;
  3502. };
  3503. /**
  3504. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3505. * @param start defines the start value
  3506. * @param end defines the end value
  3507. * @param amount max defines amount between both (between 0 and 1)
  3508. * @param result defines the Vector3 where to store the result
  3509. */
  3510. Vector3.LerpToRef = function (start, end, amount, result) {
  3511. result.x = start.x + ((end.x - start.x) * amount);
  3512. result.y = start.y + ((end.y - start.y) * amount);
  3513. result.z = start.z + ((end.z - start.z) * amount);
  3514. };
  3515. /**
  3516. * Returns the dot product (float) between the vectors "left" and "right"
  3517. * @param left defines the left operand
  3518. * @param right defines the right operand
  3519. * @returns the dot product
  3520. */
  3521. Vector3.Dot = function (left, right) {
  3522. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3523. };
  3524. /**
  3525. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3526. * The cross product is then orthogonal to both "left" and "right"
  3527. * @param left defines the left operand
  3528. * @param right defines the right operand
  3529. * @returns the cross product
  3530. */
  3531. Vector3.Cross = function (left, right) {
  3532. var result = Vector3.Zero();
  3533. Vector3.CrossToRef(left, right, result);
  3534. return result;
  3535. };
  3536. /**
  3537. * Sets the given vector "result" with the cross product of "left" and "right"
  3538. * The cross product is then orthogonal to both "left" and "right"
  3539. * @param left defines the left operand
  3540. * @param right defines the right operand
  3541. * @param result defines the Vector3 where to store the result
  3542. */
  3543. Vector3.CrossToRef = function (left, right, result) {
  3544. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3545. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3546. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3547. result.copyFrom(MathTmp.Vector3[0]);
  3548. };
  3549. /**
  3550. * Returns a new Vector3 as the normalization of the given vector
  3551. * @param vector defines the Vector3 to normalize
  3552. * @returns the new Vector3
  3553. */
  3554. Vector3.Normalize = function (vector) {
  3555. var result = Vector3.Zero();
  3556. Vector3.NormalizeToRef(vector, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the given vector "result" with the normalization of the given first vector
  3561. * @param vector defines the Vector3 to normalize
  3562. * @param result defines the Vector3 where to store the result
  3563. */
  3564. Vector3.NormalizeToRef = function (vector, result) {
  3565. result.copyFrom(vector);
  3566. result.normalize();
  3567. };
  3568. /**
  3569. * Project a Vector3 onto screen space
  3570. * @param vector defines the Vector3 to project
  3571. * @param world defines the world matrix to use
  3572. * @param transform defines the transform (view x projection) matrix to use
  3573. * @param viewport defines the screen viewport to use
  3574. * @returns the new Vector3
  3575. */
  3576. Vector3.Project = function (vector, world, transform, viewport) {
  3577. var cw = viewport.width;
  3578. var ch = viewport.height;
  3579. var cx = viewport.x;
  3580. var cy = viewport.y;
  3581. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3582. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3583. var matrix = MathTmp.Matrix[0];
  3584. world.multiplyToRef(transform, matrix);
  3585. matrix.multiplyToRef(viewportMatrix, matrix);
  3586. return Vector3.TransformCoordinates(vector, matrix);
  3587. };
  3588. /**
  3589. * Unproject from screen space to object space
  3590. * @param source defines the screen space Vector3 to use
  3591. * @param viewportWidth defines the current width of the viewport
  3592. * @param viewportHeight defines the current height of the viewport
  3593. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3594. * @param transform defines the transform (view x projection) matrix to use
  3595. * @returns the new Vector3
  3596. */
  3597. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3598. var matrix = MathTmp.Matrix[0];
  3599. world.multiplyToRef(transform, matrix);
  3600. matrix.invert();
  3601. source.x = source.x / viewportWidth * 2 - 1;
  3602. source.y = -(source.y / viewportHeight * 2 - 1);
  3603. var vector = Vector3.TransformCoordinates(source, matrix);
  3604. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3605. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3606. vector = vector.scale(1.0 / num);
  3607. }
  3608. return vector;
  3609. };
  3610. /**
  3611. * Unproject from screen space to object space
  3612. * @param source defines the screen space Vector3 to use
  3613. * @param viewportWidth defines the current width of the viewport
  3614. * @param viewportHeight defines the current height of the viewport
  3615. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3616. * @param view defines the view matrix to use
  3617. * @param projection defines the projection matrix to use
  3618. * @returns the new Vector3
  3619. */
  3620. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3621. var result = Vector3.Zero();
  3622. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3623. return result;
  3624. };
  3625. /**
  3626. * Unproject from screen space to object space
  3627. * @param source defines the screen space Vector3 to use
  3628. * @param viewportWidth defines the current width of the viewport
  3629. * @param viewportHeight defines the current height of the viewport
  3630. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3631. * @param view defines the view matrix to use
  3632. * @param projection defines the projection matrix to use
  3633. * @param result defines the Vector3 where to store the result
  3634. */
  3635. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3636. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3637. };
  3638. /**
  3639. * Unproject from screen space to object space
  3640. * @param sourceX defines the screen space x coordinate to use
  3641. * @param sourceY defines the screen space y coordinate to use
  3642. * @param sourceZ defines the screen space z coordinate to use
  3643. * @param viewportWidth defines the current width of the viewport
  3644. * @param viewportHeight defines the current height of the viewport
  3645. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3646. * @param view defines the view matrix to use
  3647. * @param projection defines the projection matrix to use
  3648. * @param result defines the Vector3 where to store the result
  3649. */
  3650. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3651. var matrix = MathTmp.Matrix[0];
  3652. world.multiplyToRef(view, matrix);
  3653. matrix.multiplyToRef(projection, matrix);
  3654. matrix.invert();
  3655. var screenSource = MathTmp.Vector3[0];
  3656. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3657. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3658. screenSource.z = 2 * sourceZ - 1.0;
  3659. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3660. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3661. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3662. result.scaleInPlace(1.0 / num);
  3663. }
  3664. };
  3665. /**
  3666. * Gets the minimal coordinate values between two Vector3
  3667. * @param left defines the first operand
  3668. * @param right defines the second operand
  3669. * @returns the new Vector3
  3670. */
  3671. Vector3.Minimize = function (left, right) {
  3672. var min = left.clone();
  3673. min.minimizeInPlace(right);
  3674. return min;
  3675. };
  3676. /**
  3677. * Gets the maximal coordinate values between two Vector3
  3678. * @param left defines the first operand
  3679. * @param right defines the second operand
  3680. * @returns the new Vector3
  3681. */
  3682. Vector3.Maximize = function (left, right) {
  3683. var max = left.clone();
  3684. max.maximizeInPlace(right);
  3685. return max;
  3686. };
  3687. /**
  3688. * Returns the distance between the vectors "value1" and "value2"
  3689. * @param value1 defines the first operand
  3690. * @param value2 defines the second operand
  3691. * @returns the distance
  3692. */
  3693. Vector3.Distance = function (value1, value2) {
  3694. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3695. };
  3696. /**
  3697. * Returns the squared distance between the vectors "value1" and "value2"
  3698. * @param value1 defines the first operand
  3699. * @param value2 defines the second operand
  3700. * @returns the squared distance
  3701. */
  3702. Vector3.DistanceSquared = function (value1, value2) {
  3703. var x = value1.x - value2.x;
  3704. var y = value1.y - value2.y;
  3705. var z = value1.z - value2.z;
  3706. return (x * x) + (y * y) + (z * z);
  3707. };
  3708. /**
  3709. * Returns a new Vector3 located at the center between "value1" and "value2"
  3710. * @param value1 defines the first operand
  3711. * @param value2 defines the second operand
  3712. * @returns the new Vector3
  3713. */
  3714. Vector3.Center = function (value1, value2) {
  3715. var center = value1.add(value2);
  3716. center.scaleInPlace(0.5);
  3717. return center;
  3718. };
  3719. /**
  3720. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3721. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3722. * to something in order to rotate it from its local system to the given target system
  3723. * Note: axis1, axis2 and axis3 are normalized during this operation
  3724. * @param axis1 defines the first axis
  3725. * @param axis2 defines the second axis
  3726. * @param axis3 defines the third axis
  3727. * @returns a new Vector3
  3728. */
  3729. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3730. var rotation = Vector3.Zero();
  3731. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3732. return rotation;
  3733. };
  3734. /**
  3735. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3736. * @param axis1 defines the first axis
  3737. * @param axis2 defines the second axis
  3738. * @param axis3 defines the third axis
  3739. * @param ref defines the Vector3 where to store the result
  3740. */
  3741. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3742. var quat = MathTmp.Quaternion[0];
  3743. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3744. quat.toEulerAnglesToRef(ref);
  3745. };
  3746. return Vector3;
  3747. }());
  3748. BABYLON.Vector3 = Vector3;
  3749. //Vector4 class created for EulerAngle class conversion to Quaternion
  3750. var Vector4 = /** @class */ (function () {
  3751. /**
  3752. * Creates a Vector4 object from the given floats.
  3753. */
  3754. function Vector4(x, y, z, w) {
  3755. this.x = x;
  3756. this.y = y;
  3757. this.z = z;
  3758. this.w = w;
  3759. }
  3760. /**
  3761. * Returns the string with the Vector4 coordinates.
  3762. */
  3763. Vector4.prototype.toString = function () {
  3764. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3765. };
  3766. /**
  3767. * Returns the string "Vector4".
  3768. */
  3769. Vector4.prototype.getClassName = function () {
  3770. return "Vector4";
  3771. };
  3772. /**
  3773. * Returns the Vector4 hash code.
  3774. */
  3775. Vector4.prototype.getHashCode = function () {
  3776. var hash = this.x || 0;
  3777. hash = (hash * 397) ^ (this.y || 0);
  3778. hash = (hash * 397) ^ (this.z || 0);
  3779. hash = (hash * 397) ^ (this.w || 0);
  3780. return hash;
  3781. };
  3782. // Operators
  3783. /**
  3784. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3785. */
  3786. Vector4.prototype.asArray = function () {
  3787. var result = new Array();
  3788. this.toArray(result, 0);
  3789. return result;
  3790. };
  3791. /**
  3792. * Populates the given array from the given index with the Vector4 coordinates.
  3793. * Returns the Vector4.
  3794. */
  3795. Vector4.prototype.toArray = function (array, index) {
  3796. if (index === undefined) {
  3797. index = 0;
  3798. }
  3799. array[index] = this.x;
  3800. array[index + 1] = this.y;
  3801. array[index + 2] = this.z;
  3802. array[index + 3] = this.w;
  3803. return this;
  3804. };
  3805. /**
  3806. * Adds the given vector to the current Vector4.
  3807. * Returns the updated Vector4.
  3808. */
  3809. Vector4.prototype.addInPlace = function (otherVector) {
  3810. this.x += otherVector.x;
  3811. this.y += otherVector.y;
  3812. this.z += otherVector.z;
  3813. this.w += otherVector.w;
  3814. return this;
  3815. };
  3816. /**
  3817. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3818. */
  3819. Vector4.prototype.add = function (otherVector) {
  3820. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3821. };
  3822. /**
  3823. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3824. * Returns the current Vector4.
  3825. */
  3826. Vector4.prototype.addToRef = function (otherVector, result) {
  3827. result.x = this.x + otherVector.x;
  3828. result.y = this.y + otherVector.y;
  3829. result.z = this.z + otherVector.z;
  3830. result.w = this.w + otherVector.w;
  3831. return this;
  3832. };
  3833. /**
  3834. * Subtract in place the given vector from the current Vector4.
  3835. * Returns the updated Vector4.
  3836. */
  3837. Vector4.prototype.subtractInPlace = function (otherVector) {
  3838. this.x -= otherVector.x;
  3839. this.y -= otherVector.y;
  3840. this.z -= otherVector.z;
  3841. this.w -= otherVector.w;
  3842. return this;
  3843. };
  3844. /**
  3845. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3846. */
  3847. Vector4.prototype.subtract = function (otherVector) {
  3848. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3849. };
  3850. /**
  3851. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3852. * Returns the current Vector4.
  3853. */
  3854. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3855. result.x = this.x - otherVector.x;
  3856. result.y = this.y - otherVector.y;
  3857. result.z = this.z - otherVector.z;
  3858. result.w = this.w - otherVector.w;
  3859. return this;
  3860. };
  3861. /**
  3862. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3863. */
  3864. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3865. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3866. };
  3867. /**
  3868. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3869. * Returns the current Vector4.
  3870. */
  3871. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3872. result.x = this.x - x;
  3873. result.y = this.y - y;
  3874. result.z = this.z - z;
  3875. result.w = this.w - w;
  3876. return this;
  3877. };
  3878. /**
  3879. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3880. */
  3881. Vector4.prototype.negate = function () {
  3882. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3883. };
  3884. /**
  3885. * Multiplies the current Vector4 coordinates by scale (float).
  3886. * Returns the updated Vector4.
  3887. */
  3888. Vector4.prototype.scaleInPlace = function (scale) {
  3889. this.x *= scale;
  3890. this.y *= scale;
  3891. this.z *= scale;
  3892. this.w *= scale;
  3893. return this;
  3894. };
  3895. /**
  3896. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3897. */
  3898. Vector4.prototype.scale = function (scale) {
  3899. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3900. };
  3901. /**
  3902. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3903. * Returns the current Vector4.
  3904. */
  3905. Vector4.prototype.scaleToRef = function (scale, result) {
  3906. result.x = this.x * scale;
  3907. result.y = this.y * scale;
  3908. result.z = this.z * scale;
  3909. result.w = this.w * scale;
  3910. return this;
  3911. };
  3912. /**
  3913. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3914. * @param scale defines the scale factor
  3915. * @param result defines the Vector4 object where to store the result
  3916. * @returns the unmodified current Vector4
  3917. */
  3918. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3919. result.x += this.x * scale;
  3920. result.y += this.y * scale;
  3921. result.z += this.z * scale;
  3922. result.w += this.w * scale;
  3923. return this;
  3924. };
  3925. /**
  3926. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3927. */
  3928. Vector4.prototype.equals = function (otherVector) {
  3929. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3930. };
  3931. /**
  3932. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3933. */
  3934. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3935. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3936. return otherVector
  3937. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3938. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3939. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3940. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3941. };
  3942. /**
  3943. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3944. */
  3945. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3946. return this.x === x && this.y === y && this.z === z && this.w === w;
  3947. };
  3948. /**
  3949. * Multiplies in place the current Vector4 by the given one.
  3950. * Returns the updated Vector4.
  3951. */
  3952. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3953. this.x *= otherVector.x;
  3954. this.y *= otherVector.y;
  3955. this.z *= otherVector.z;
  3956. this.w *= otherVector.w;
  3957. return this;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3961. */
  3962. Vector4.prototype.multiply = function (otherVector) {
  3963. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3964. };
  3965. /**
  3966. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3967. * Returns the current Vector4.
  3968. */
  3969. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3970. result.x = this.x * otherVector.x;
  3971. result.y = this.y * otherVector.y;
  3972. result.z = this.z * otherVector.z;
  3973. result.w = this.w * otherVector.w;
  3974. return this;
  3975. };
  3976. /**
  3977. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3978. */
  3979. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3980. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3981. };
  3982. /**
  3983. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3984. */
  3985. Vector4.prototype.divide = function (otherVector) {
  3986. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3987. };
  3988. /**
  3989. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3990. * Returns the current Vector4.
  3991. */
  3992. Vector4.prototype.divideToRef = function (otherVector, result) {
  3993. result.x = this.x / otherVector.x;
  3994. result.y = this.y / otherVector.y;
  3995. result.z = this.z / otherVector.z;
  3996. result.w = this.w / otherVector.w;
  3997. return this;
  3998. };
  3999. /**
  4000. * Divides the current Vector3 coordinates by the given ones.
  4001. * @returns the updated Vector3.
  4002. */
  4003. Vector4.prototype.divideInPlace = function (otherVector) {
  4004. return this.divideToRef(otherVector, this);
  4005. };
  4006. /**
  4007. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4008. * @param other defines the second operand
  4009. * @returns the current updated Vector4
  4010. */
  4011. Vector4.prototype.minimizeInPlace = function (other) {
  4012. if (other.x < this.x)
  4013. this.x = other.x;
  4014. if (other.y < this.y)
  4015. this.y = other.y;
  4016. if (other.z < this.z)
  4017. this.z = other.z;
  4018. if (other.w < this.w)
  4019. this.w = other.w;
  4020. return this;
  4021. };
  4022. /**
  4023. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4024. * @param other defines the second operand
  4025. * @returns the current updated Vector4
  4026. */
  4027. Vector4.prototype.maximizeInPlace = function (other) {
  4028. if (other.x > this.x)
  4029. this.x = other.x;
  4030. if (other.y > this.y)
  4031. this.y = other.y;
  4032. if (other.z > this.z)
  4033. this.z = other.z;
  4034. if (other.w > this.w)
  4035. this.w = other.w;
  4036. return this;
  4037. };
  4038. // Properties
  4039. /**
  4040. * Returns the Vector4 length (float).
  4041. */
  4042. Vector4.prototype.length = function () {
  4043. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4044. };
  4045. /**
  4046. * Returns the Vector4 squared length (float).
  4047. */
  4048. Vector4.prototype.lengthSquared = function () {
  4049. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4050. };
  4051. // Methods
  4052. /**
  4053. * Normalizes in place the Vector4.
  4054. * Returns the updated Vector4.
  4055. */
  4056. Vector4.prototype.normalize = function () {
  4057. var len = this.length();
  4058. if (len === 0)
  4059. return this;
  4060. var num = 1.0 / len;
  4061. this.x *= num;
  4062. this.y *= num;
  4063. this.z *= num;
  4064. this.w *= num;
  4065. return this;
  4066. };
  4067. /**
  4068. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4069. */
  4070. Vector4.prototype.toVector3 = function () {
  4071. return new Vector3(this.x, this.y, this.z);
  4072. };
  4073. /**
  4074. * Returns a new Vector4 copied from the current one.
  4075. */
  4076. Vector4.prototype.clone = function () {
  4077. return new Vector4(this.x, this.y, this.z, this.w);
  4078. };
  4079. /**
  4080. * Updates the current Vector4 with the given one coordinates.
  4081. * Returns the updated Vector4.
  4082. */
  4083. Vector4.prototype.copyFrom = function (source) {
  4084. this.x = source.x;
  4085. this.y = source.y;
  4086. this.z = source.z;
  4087. this.w = source.w;
  4088. return this;
  4089. };
  4090. /**
  4091. * Updates the current Vector4 coordinates with the given floats.
  4092. * Returns the updated Vector4.
  4093. */
  4094. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4095. this.x = x;
  4096. this.y = y;
  4097. this.z = z;
  4098. this.w = w;
  4099. return this;
  4100. };
  4101. /**
  4102. * Updates the current Vector4 coordinates with the given floats.
  4103. * Returns the updated Vector4.
  4104. */
  4105. Vector4.prototype.set = function (x, y, z, w) {
  4106. return this.copyFromFloats(x, y, z, w);
  4107. };
  4108. // Statics
  4109. /**
  4110. * Returns a new Vector4 set from the starting index of the given array.
  4111. */
  4112. Vector4.FromArray = function (array, offset) {
  4113. if (!offset) {
  4114. offset = 0;
  4115. }
  4116. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4117. };
  4118. /**
  4119. * Updates the given vector "result" from the starting index of the given array.
  4120. */
  4121. Vector4.FromArrayToRef = function (array, offset, result) {
  4122. result.x = array[offset];
  4123. result.y = array[offset + 1];
  4124. result.z = array[offset + 2];
  4125. result.w = array[offset + 3];
  4126. };
  4127. /**
  4128. * Updates the given vector "result" from the starting index of the given Float32Array.
  4129. */
  4130. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4131. Vector4.FromArrayToRef(array, offset, result);
  4132. };
  4133. /**
  4134. * Updates the given vector "result" coordinates from the given floats.
  4135. */
  4136. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4137. result.x = x;
  4138. result.y = y;
  4139. result.z = z;
  4140. result.w = w;
  4141. };
  4142. /**
  4143. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4144. */
  4145. Vector4.Zero = function () {
  4146. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4147. };
  4148. /**
  4149. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4150. */
  4151. Vector4.One = function () {
  4152. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4153. };
  4154. /**
  4155. * Returns a new normalized Vector4 from the given one.
  4156. */
  4157. Vector4.Normalize = function (vector) {
  4158. var result = Vector4.Zero();
  4159. Vector4.NormalizeToRef(vector, result);
  4160. return result;
  4161. };
  4162. /**
  4163. * Updates the given vector "result" from the normalization of the given one.
  4164. */
  4165. Vector4.NormalizeToRef = function (vector, result) {
  4166. result.copyFrom(vector);
  4167. result.normalize();
  4168. };
  4169. Vector4.Minimize = function (left, right) {
  4170. var min = left.clone();
  4171. min.minimizeInPlace(right);
  4172. return min;
  4173. };
  4174. Vector4.Maximize = function (left, right) {
  4175. var max = left.clone();
  4176. max.maximizeInPlace(right);
  4177. return max;
  4178. };
  4179. /**
  4180. * Returns the distance (float) between the vectors "value1" and "value2".
  4181. */
  4182. Vector4.Distance = function (value1, value2) {
  4183. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4184. };
  4185. /**
  4186. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4187. */
  4188. Vector4.DistanceSquared = function (value1, value2) {
  4189. var x = value1.x - value2.x;
  4190. var y = value1.y - value2.y;
  4191. var z = value1.z - value2.z;
  4192. var w = value1.w - value2.w;
  4193. return (x * x) + (y * y) + (z * z) + (w * w);
  4194. };
  4195. /**
  4196. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4197. */
  4198. Vector4.Center = function (value1, value2) {
  4199. var center = value1.add(value2);
  4200. center.scaleInPlace(0.5);
  4201. return center;
  4202. };
  4203. /**
  4204. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4205. * This methods computes transformed normalized direction vectors only.
  4206. */
  4207. Vector4.TransformNormal = function (vector, transformation) {
  4208. var result = Vector4.Zero();
  4209. Vector4.TransformNormalToRef(vector, transformation, result);
  4210. return result;
  4211. };
  4212. /**
  4213. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4214. * This methods computes transformed normalized direction vectors only.
  4215. */
  4216. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4217. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4218. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4219. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4220. result.x = x;
  4221. result.y = y;
  4222. result.z = z;
  4223. result.w = vector.w;
  4224. };
  4225. /**
  4226. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4227. * This methods computes transformed normalized direction vectors only.
  4228. */
  4229. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4230. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4231. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4232. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4233. result.w = w;
  4234. };
  4235. return Vector4;
  4236. }());
  4237. BABYLON.Vector4 = Vector4;
  4238. var Size = /** @class */ (function () {
  4239. /**
  4240. * Creates a Size object from the given width and height (floats).
  4241. */
  4242. function Size(width, height) {
  4243. this.width = width;
  4244. this.height = height;
  4245. }
  4246. // Returns a string with the Size width and height.
  4247. Size.prototype.toString = function () {
  4248. return "{W: " + this.width + ", H: " + this.height + "}";
  4249. };
  4250. /**
  4251. * Returns the string "Size"
  4252. */
  4253. Size.prototype.getClassName = function () {
  4254. return "Size";
  4255. };
  4256. /**
  4257. * Returns the Size hash code.
  4258. */
  4259. Size.prototype.getHashCode = function () {
  4260. var hash = this.width || 0;
  4261. hash = (hash * 397) ^ (this.height || 0);
  4262. return hash;
  4263. };
  4264. /**
  4265. * Updates the current size from the given one.
  4266. * Returns the updated Size.
  4267. */
  4268. Size.prototype.copyFrom = function (src) {
  4269. this.width = src.width;
  4270. this.height = src.height;
  4271. };
  4272. /**
  4273. * Updates in place the current Size from the given floats.
  4274. * Returns the updated Size.
  4275. */
  4276. Size.prototype.copyFromFloats = function (width, height) {
  4277. this.width = width;
  4278. this.height = height;
  4279. return this;
  4280. };
  4281. /**
  4282. * Updates in place the current Size from the given floats.
  4283. * Returns the updated Size.
  4284. */
  4285. Size.prototype.set = function (width, height) {
  4286. return this.copyFromFloats(width, height);
  4287. };
  4288. /**
  4289. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4290. */
  4291. Size.prototype.multiplyByFloats = function (w, h) {
  4292. return new Size(this.width * w, this.height * h);
  4293. };
  4294. /**
  4295. * Returns a new Size copied from the given one.
  4296. */
  4297. Size.prototype.clone = function () {
  4298. return new Size(this.width, this.height);
  4299. };
  4300. /**
  4301. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4302. */
  4303. Size.prototype.equals = function (other) {
  4304. if (!other) {
  4305. return false;
  4306. }
  4307. return (this.width === other.width) && (this.height === other.height);
  4308. };
  4309. Object.defineProperty(Size.prototype, "surface", {
  4310. /**
  4311. * Returns the surface of the Size : width * height (float).
  4312. */
  4313. get: function () {
  4314. return this.width * this.height;
  4315. },
  4316. enumerable: true,
  4317. configurable: true
  4318. });
  4319. /**
  4320. * Returns a new Size set to (0.0, 0.0)
  4321. */
  4322. Size.Zero = function () {
  4323. return new Size(0.0, 0.0);
  4324. };
  4325. /**
  4326. * Returns a new Size set as the addition result of the current Size and the given one.
  4327. */
  4328. Size.prototype.add = function (otherSize) {
  4329. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4330. return r;
  4331. };
  4332. /**
  4333. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4334. */
  4335. Size.prototype.subtract = function (otherSize) {
  4336. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4337. return r;
  4338. };
  4339. /**
  4340. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4341. */
  4342. Size.Lerp = function (start, end, amount) {
  4343. var w = start.width + ((end.width - start.width) * amount);
  4344. var h = start.height + ((end.height - start.height) * amount);
  4345. return new Size(w, h);
  4346. };
  4347. return Size;
  4348. }());
  4349. BABYLON.Size = Size;
  4350. /**
  4351. * Class used to store quaternion data
  4352. * @see https://en.wikipedia.org/wiki/Quaternion
  4353. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4354. */
  4355. var Quaternion = /** @class */ (function () {
  4356. /**
  4357. * Creates a new Quaternion from the given floats
  4358. * @param x defines the first component (0 by default)
  4359. * @param y defines the second component (0 by default)
  4360. * @param z defines the third component (0 by default)
  4361. * @param w defines the fourth component (1.0 by default)
  4362. */
  4363. function Quaternion(
  4364. /** defines the first component (0 by default) */
  4365. x,
  4366. /** defines the second component (0 by default) */
  4367. y,
  4368. /** defines the third component (0 by default) */
  4369. z,
  4370. /** defines the fourth component (1.0 by default) */
  4371. w) {
  4372. if (x === void 0) { x = 0.0; }
  4373. if (y === void 0) { y = 0.0; }
  4374. if (z === void 0) { z = 0.0; }
  4375. if (w === void 0) { w = 1.0; }
  4376. this.x = x;
  4377. this.y = y;
  4378. this.z = z;
  4379. this.w = w;
  4380. }
  4381. /**
  4382. * Gets a string representation for the current quaternion
  4383. * @returns a string with the Quaternion coordinates
  4384. */
  4385. Quaternion.prototype.toString = function () {
  4386. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4387. };
  4388. /**
  4389. * Gets the class name of the quaternion
  4390. * @returns the string "Quaternion"
  4391. */
  4392. Quaternion.prototype.getClassName = function () {
  4393. return "Quaternion";
  4394. };
  4395. /**
  4396. * Gets a hash code for this quaternion
  4397. * @returns the quaternion hash code
  4398. */
  4399. Quaternion.prototype.getHashCode = function () {
  4400. var hash = this.x || 0;
  4401. hash = (hash * 397) ^ (this.y || 0);
  4402. hash = (hash * 397) ^ (this.z || 0);
  4403. hash = (hash * 397) ^ (this.w || 0);
  4404. return hash;
  4405. };
  4406. /**
  4407. * Copy the quaternion to an array
  4408. * @returns a new array populated with 4 elements from the quaternion coordinates
  4409. */
  4410. Quaternion.prototype.asArray = function () {
  4411. return [this.x, this.y, this.z, this.w];
  4412. };
  4413. /**
  4414. * Check if two quaternions are equals
  4415. * @param otherQuaternion defines the second operand
  4416. * @return true if the current quaternion and the given one coordinates are strictly equals
  4417. */
  4418. Quaternion.prototype.equals = function (otherQuaternion) {
  4419. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4420. };
  4421. /**
  4422. * Clone the current quaternion
  4423. * @returns a new quaternion copied from the current one
  4424. */
  4425. Quaternion.prototype.clone = function () {
  4426. return new Quaternion(this.x, this.y, this.z, this.w);
  4427. };
  4428. /**
  4429. * Copy a quaternion to the current one
  4430. * @param other defines the other quaternion
  4431. * @returns the updated current quaternion
  4432. */
  4433. Quaternion.prototype.copyFrom = function (other) {
  4434. this.x = other.x;
  4435. this.y = other.y;
  4436. this.z = other.z;
  4437. this.w = other.w;
  4438. return this;
  4439. };
  4440. /**
  4441. * Updates the current quaternion with the given float coordinates
  4442. * @param x defines the x coordinate
  4443. * @param y defines the y coordinate
  4444. * @param z defines the z coordinate
  4445. * @param w defines the w coordinate
  4446. * @returns the updated current quaternion
  4447. */
  4448. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4449. this.x = x;
  4450. this.y = y;
  4451. this.z = z;
  4452. this.w = w;
  4453. return this;
  4454. };
  4455. /**
  4456. * Updates the current quaternion from the given float coordinates
  4457. * @param x defines the x coordinate
  4458. * @param y defines the y coordinate
  4459. * @param z defines the z coordinate
  4460. * @param w defines the w coordinate
  4461. * @returns the updated current quaternion
  4462. */
  4463. Quaternion.prototype.set = function (x, y, z, w) {
  4464. return this.copyFromFloats(x, y, z, w);
  4465. };
  4466. /**
  4467. * Adds two quaternions
  4468. * @param other defines the second operand
  4469. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4470. */
  4471. Quaternion.prototype.add = function (other) {
  4472. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4473. };
  4474. /**
  4475. * Add a quaternion to the current one
  4476. * @param other defines the quaternion to add
  4477. * @returns the current quaternion
  4478. */
  4479. Quaternion.prototype.addInPlace = function (other) {
  4480. this.x += other.x;
  4481. this.y += other.y;
  4482. this.z += other.z;
  4483. this.w += other.w;
  4484. return this;
  4485. };
  4486. /**
  4487. * Subtract two quaternions
  4488. * @param other defines the second operand
  4489. * @returns a new quaternion as the subtraction result of the given one from the current one
  4490. */
  4491. Quaternion.prototype.subtract = function (other) {
  4492. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4493. };
  4494. /**
  4495. * Multiplies the current quaternion by a scale factor
  4496. * @param value defines the scale factor
  4497. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4498. */
  4499. Quaternion.prototype.scale = function (value) {
  4500. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4501. };
  4502. /**
  4503. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4504. * @param scale defines the scale factor
  4505. * @param result defines the Quaternion object where to store the result
  4506. * @returns the unmodified current quaternion
  4507. */
  4508. Quaternion.prototype.scaleToRef = function (scale, result) {
  4509. result.x = this.x * scale;
  4510. result.y = this.y * scale;
  4511. result.z = this.z * scale;
  4512. result.w = this.w * scale;
  4513. return this;
  4514. };
  4515. /**
  4516. * Multiplies in place the current quaternion by a scale factor
  4517. * @param value defines the scale factor
  4518. * @returns the current modified quaternion
  4519. */
  4520. Quaternion.prototype.scaleInPlace = function (value) {
  4521. this.x *= value;
  4522. this.y *= value;
  4523. this.z *= value;
  4524. this.w *= value;
  4525. return this;
  4526. };
  4527. /**
  4528. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4529. * @param scale defines the scale factor
  4530. * @param result defines the Quaternion object where to store the result
  4531. * @returns the unmodified current quaternion
  4532. */
  4533. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4534. result.x += this.x * scale;
  4535. result.y += this.y * scale;
  4536. result.z += this.z * scale;
  4537. result.w += this.w * scale;
  4538. return this;
  4539. };
  4540. /**
  4541. * Multiplies two quaternions
  4542. * @param q1 defines the second operand
  4543. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4544. */
  4545. Quaternion.prototype.multiply = function (q1) {
  4546. var result = new Quaternion(0, 0, 0, 1.0);
  4547. this.multiplyToRef(q1, result);
  4548. return result;
  4549. };
  4550. /**
  4551. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4552. * @param q1 defines the second operand
  4553. * @param result defines the target quaternion
  4554. * @returns the current quaternion
  4555. */
  4556. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4557. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4558. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4559. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4560. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4561. result.copyFromFloats(x, y, z, w);
  4562. return this;
  4563. };
  4564. /**
  4565. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4566. * @param q1 defines the second operand
  4567. * @returns the currentupdated quaternion
  4568. */
  4569. Quaternion.prototype.multiplyInPlace = function (q1) {
  4570. this.multiplyToRef(q1, this);
  4571. return this;
  4572. };
  4573. /**
  4574. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4575. * @param ref defines the target quaternion
  4576. * @returns the current quaternion
  4577. */
  4578. Quaternion.prototype.conjugateToRef = function (ref) {
  4579. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4580. return this;
  4581. };
  4582. /**
  4583. * Conjugates in place (1-q) the current quaternion
  4584. * @returns the current updated quaternion
  4585. */
  4586. Quaternion.prototype.conjugateInPlace = function () {
  4587. this.x *= -1;
  4588. this.y *= -1;
  4589. this.z *= -1;
  4590. return this;
  4591. };
  4592. /**
  4593. * Conjugates in place (1-q) the current quaternion
  4594. * @returns a new quaternion
  4595. */
  4596. Quaternion.prototype.conjugate = function () {
  4597. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4598. return result;
  4599. };
  4600. /**
  4601. * Gets length of current quaternion
  4602. * @returns the quaternion length (float)
  4603. */
  4604. Quaternion.prototype.length = function () {
  4605. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4606. };
  4607. /**
  4608. * Normalize in place the current quaternion
  4609. * @returns the current updated quaternion
  4610. */
  4611. Quaternion.prototype.normalize = function () {
  4612. var length = 1.0 / this.length();
  4613. this.x *= length;
  4614. this.y *= length;
  4615. this.z *= length;
  4616. this.w *= length;
  4617. return this;
  4618. };
  4619. /**
  4620. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4621. * @param order is a reserved parameter and is ignore for now
  4622. * @returns a new Vector3 containing the Euler angles
  4623. */
  4624. Quaternion.prototype.toEulerAngles = function (order) {
  4625. if (order === void 0) { order = "YZX"; }
  4626. var result = Vector3.Zero();
  4627. this.toEulerAnglesToRef(result, order);
  4628. return result;
  4629. };
  4630. /**
  4631. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4632. * @param result defines the vector which will be filled with the Euler angles
  4633. * @param order is a reserved parameter and is ignore for now
  4634. * @returns the current unchanged quaternion
  4635. */
  4636. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4637. if (order === void 0) { order = "YZX"; }
  4638. var qz = this.z;
  4639. var qx = this.x;
  4640. var qy = this.y;
  4641. var qw = this.w;
  4642. var sqw = qw * qw;
  4643. var sqz = qz * qz;
  4644. var sqx = qx * qx;
  4645. var sqy = qy * qy;
  4646. var zAxisY = qy * qz - qx * qw;
  4647. var limit = .4999999;
  4648. if (zAxisY < -limit) {
  4649. result.y = 2 * Math.atan2(qy, qw);
  4650. result.x = Math.PI / 2;
  4651. result.z = 0;
  4652. }
  4653. else if (zAxisY > limit) {
  4654. result.y = 2 * Math.atan2(qy, qw);
  4655. result.x = -Math.PI / 2;
  4656. result.z = 0;
  4657. }
  4658. else {
  4659. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4660. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4661. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4662. }
  4663. return this;
  4664. };
  4665. /**
  4666. * Updates the given rotation matrix with the current quaternion values
  4667. * @param result defines the target matrix
  4668. * @returns the current unchanged quaternion
  4669. */
  4670. Quaternion.prototype.toRotationMatrix = function (result) {
  4671. var xx = this.x * this.x;
  4672. var yy = this.y * this.y;
  4673. var zz = this.z * this.z;
  4674. var xy = this.x * this.y;
  4675. var zw = this.z * this.w;
  4676. var zx = this.z * this.x;
  4677. var yw = this.y * this.w;
  4678. var yz = this.y * this.z;
  4679. var xw = this.x * this.w;
  4680. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4681. result.m[1] = 2.0 * (xy + zw);
  4682. result.m[2] = 2.0 * (zx - yw);
  4683. result.m[3] = 0;
  4684. result.m[4] = 2.0 * (xy - zw);
  4685. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4686. result.m[6] = 2.0 * (yz + xw);
  4687. result.m[7] = 0;
  4688. result.m[8] = 2.0 * (zx + yw);
  4689. result.m[9] = 2.0 * (yz - xw);
  4690. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4691. result.m[11] = 0;
  4692. result.m[12] = 0;
  4693. result.m[13] = 0;
  4694. result.m[14] = 0;
  4695. result.m[15] = 1.0;
  4696. result._markAsUpdated();
  4697. return this;
  4698. };
  4699. /**
  4700. * Updates the current quaternion from the given rotation matrix values
  4701. * @param matrix defines the source matrix
  4702. * @returns the current updated quaternion
  4703. */
  4704. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4705. Quaternion.FromRotationMatrixToRef(matrix, this);
  4706. return this;
  4707. };
  4708. // Statics
  4709. /**
  4710. * Creates a new quaternion from a rotation matrix
  4711. * @param matrix defines the source matrix
  4712. * @returns a new quaternion created from the given rotation matrix values
  4713. */
  4714. Quaternion.FromRotationMatrix = function (matrix) {
  4715. var result = new Quaternion();
  4716. Quaternion.FromRotationMatrixToRef(matrix, result);
  4717. return result;
  4718. };
  4719. /**
  4720. * Updates the given quaternion with the given rotation matrix values
  4721. * @param matrix defines the source matrix
  4722. * @param result defines the target quaternion
  4723. */
  4724. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4725. var data = matrix.m;
  4726. var m11 = data[0], m12 = data[4], m13 = data[8];
  4727. var m21 = data[1], m22 = data[5], m23 = data[9];
  4728. var m31 = data[2], m32 = data[6], m33 = data[10];
  4729. var trace = m11 + m22 + m33;
  4730. var s;
  4731. if (trace > 0) {
  4732. s = 0.5 / Math.sqrt(trace + 1.0);
  4733. result.w = 0.25 / s;
  4734. result.x = (m32 - m23) * s;
  4735. result.y = (m13 - m31) * s;
  4736. result.z = (m21 - m12) * s;
  4737. }
  4738. else if (m11 > m22 && m11 > m33) {
  4739. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4740. result.w = (m32 - m23) / s;
  4741. result.x = 0.25 * s;
  4742. result.y = (m12 + m21) / s;
  4743. result.z = (m13 + m31) / s;
  4744. }
  4745. else if (m22 > m33) {
  4746. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4747. result.w = (m13 - m31) / s;
  4748. result.x = (m12 + m21) / s;
  4749. result.y = 0.25 * s;
  4750. result.z = (m23 + m32) / s;
  4751. }
  4752. else {
  4753. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4754. result.w = (m21 - m12) / s;
  4755. result.x = (m13 + m31) / s;
  4756. result.y = (m23 + m32) / s;
  4757. result.z = 0.25 * s;
  4758. }
  4759. };
  4760. /**
  4761. * Returns the dot product (float) between the quaternions "left" and "right"
  4762. * @param left defines the left operand
  4763. * @param right defines the right operand
  4764. * @returns the dot product
  4765. */
  4766. Quaternion.Dot = function (left, right) {
  4767. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4768. };
  4769. /**
  4770. * Checks if the two quaternions are close to each other
  4771. * @param quat0 defines the first quaternion to check
  4772. * @param quat1 defines the second quaternion to check
  4773. * @returns true if the two quaternions are close to each other
  4774. */
  4775. Quaternion.AreClose = function (quat0, quat1) {
  4776. var dot = Quaternion.Dot(quat0, quat1);
  4777. return dot >= 0;
  4778. };
  4779. /**
  4780. * Creates an empty quaternion
  4781. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4782. */
  4783. Quaternion.Zero = function () {
  4784. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4785. };
  4786. /**
  4787. * Inverse a given quaternion
  4788. * @param q defines the source quaternion
  4789. * @returns a new quaternion as the inverted current quaternion
  4790. */
  4791. Quaternion.Inverse = function (q) {
  4792. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4793. };
  4794. /**
  4795. * Creates an identity quaternion
  4796. * @returns the identity quaternion
  4797. */
  4798. Quaternion.Identity = function () {
  4799. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4800. };
  4801. /**
  4802. * Gets a boolean indicating if the given quaternion is identity
  4803. * @param quaternion defines the quaternion to check
  4804. * @returns true if the quaternion is identity
  4805. */
  4806. Quaternion.IsIdentity = function (quaternion) {
  4807. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4808. };
  4809. /**
  4810. * Creates a quaternion from a rotation around an axis
  4811. * @param axis defines the axis to use
  4812. * @param angle defines the angle to use
  4813. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4814. */
  4815. Quaternion.RotationAxis = function (axis, angle) {
  4816. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4817. };
  4818. /**
  4819. * Creates a rotation around an axis and stores it into the given quaternion
  4820. * @param axis defines the axis to use
  4821. * @param angle defines the angle to use
  4822. * @param result defines the target quaternion
  4823. * @returns the target quaternion
  4824. */
  4825. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4826. var sin = Math.sin(angle / 2);
  4827. axis.normalize();
  4828. result.w = Math.cos(angle / 2);
  4829. result.x = axis.x * sin;
  4830. result.y = axis.y * sin;
  4831. result.z = axis.z * sin;
  4832. return result;
  4833. };
  4834. /**
  4835. * Creates a new quaternion from data stored into an array
  4836. * @param array defines the data source
  4837. * @param offset defines the offset in the source array where the data starts
  4838. * @returns a new quaternion
  4839. */
  4840. Quaternion.FromArray = function (array, offset) {
  4841. if (!offset) {
  4842. offset = 0;
  4843. }
  4844. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4845. };
  4846. /**
  4847. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4848. * @param yaw defines the rotation around Y axis
  4849. * @param pitch defines the rotation around X axis
  4850. * @param roll defines the rotation around Z axis
  4851. * @returns the new quaternion
  4852. */
  4853. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4854. var q = new Quaternion();
  4855. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4856. return q;
  4857. };
  4858. /**
  4859. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4860. * @param yaw defines the rotation around Y axis
  4861. * @param pitch defines the rotation around X axis
  4862. * @param roll defines the rotation around Z axis
  4863. * @param result defines the target quaternion
  4864. */
  4865. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4866. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4867. var halfRoll = roll * 0.5;
  4868. var halfPitch = pitch * 0.5;
  4869. var halfYaw = yaw * 0.5;
  4870. var sinRoll = Math.sin(halfRoll);
  4871. var cosRoll = Math.cos(halfRoll);
  4872. var sinPitch = Math.sin(halfPitch);
  4873. var cosPitch = Math.cos(halfPitch);
  4874. var sinYaw = Math.sin(halfYaw);
  4875. var cosYaw = Math.cos(halfYaw);
  4876. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4877. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4878. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4879. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4880. };
  4881. /**
  4882. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4883. * @param alpha defines the rotation around first axis
  4884. * @param beta defines the rotation around second axis
  4885. * @param gamma defines the rotation around third axis
  4886. * @returns the new quaternion
  4887. */
  4888. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4889. var result = new Quaternion();
  4890. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4891. return result;
  4892. };
  4893. /**
  4894. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4895. * @param alpha defines the rotation around first axis
  4896. * @param beta defines the rotation around second axis
  4897. * @param gamma defines the rotation around third axis
  4898. * @param result defines the target quaternion
  4899. */
  4900. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4901. // Produces a quaternion from Euler angles in the z-x-z orientation
  4902. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4903. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4904. var halfBeta = beta * 0.5;
  4905. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4906. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4907. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4908. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4909. };
  4910. /**
  4911. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4912. * @param axis1 defines the first axis
  4913. * @param axis2 defines the second axis
  4914. * @param axis3 defines the third axis
  4915. * @returns the new quaternion
  4916. */
  4917. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4918. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4919. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4920. return quat;
  4921. };
  4922. /**
  4923. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4924. * @param axis1 defines the first axis
  4925. * @param axis2 defines the second axis
  4926. * @param axis3 defines the third axis
  4927. * @param ref defines the target quaternion
  4928. */
  4929. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4930. var rotMat = MathTmp.Matrix[0];
  4931. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4932. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4933. };
  4934. /**
  4935. * Interpolates between two quaternions
  4936. * @param left defines first quaternion
  4937. * @param right defines second quaternion
  4938. * @param amount defines the gradient to use
  4939. * @returns the new interpolated quaternion
  4940. */
  4941. Quaternion.Slerp = function (left, right, amount) {
  4942. var result = Quaternion.Identity();
  4943. Quaternion.SlerpToRef(left, right, amount, result);
  4944. return result;
  4945. };
  4946. /**
  4947. * Interpolates between two quaternions and stores it into a target quaternion
  4948. * @param left defines first quaternion
  4949. * @param right defines second quaternion
  4950. * @param amount defines the gradient to use
  4951. * @param result defines the target quaternion
  4952. */
  4953. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4954. var num2;
  4955. var num3;
  4956. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4957. var flag = false;
  4958. if (num4 < 0) {
  4959. flag = true;
  4960. num4 = -num4;
  4961. }
  4962. if (num4 > 0.999999) {
  4963. num3 = 1 - amount;
  4964. num2 = flag ? -amount : amount;
  4965. }
  4966. else {
  4967. var num5 = Math.acos(num4);
  4968. var num6 = (1.0 / Math.sin(num5));
  4969. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4970. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4971. }
  4972. result.x = (num3 * left.x) + (num2 * right.x);
  4973. result.y = (num3 * left.y) + (num2 * right.y);
  4974. result.z = (num3 * left.z) + (num2 * right.z);
  4975. result.w = (num3 * left.w) + (num2 * right.w);
  4976. };
  4977. /**
  4978. * Interpolate between two quaternions using Hermite interpolation
  4979. * @param value1 defines first quaternion
  4980. * @param tangent1 defines the incoming tangent
  4981. * @param value2 defines second quaternion
  4982. * @param tangent2 defines the outgoing tangent
  4983. * @param amount defines the target quaternion
  4984. * @returns the new interpolated quaternion
  4985. */
  4986. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4987. var squared = amount * amount;
  4988. var cubed = amount * squared;
  4989. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4990. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4991. var part3 = (cubed - (2.0 * squared)) + amount;
  4992. var part4 = cubed - squared;
  4993. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4994. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4995. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4996. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4997. return new Quaternion(x, y, z, w);
  4998. };
  4999. return Quaternion;
  5000. }());
  5001. BABYLON.Quaternion = Quaternion;
  5002. /**
  5003. * Class used to store matrix data (4x4)
  5004. */
  5005. var Matrix = /** @class */ (function () {
  5006. /**
  5007. * Creates an empty matrix (filled with zeros)
  5008. */
  5009. function Matrix() {
  5010. this._isIdentity = false;
  5011. this._isIdentityDirty = true;
  5012. /**
  5013. * Gets or sets the internal data of the matrix
  5014. */
  5015. this.m = new Float32Array(16);
  5016. this._markAsUpdated();
  5017. }
  5018. /** @hidden */
  5019. Matrix.prototype._markAsUpdated = function () {
  5020. this.updateFlag = Matrix._updateFlagSeed++;
  5021. this._isIdentityDirty = true;
  5022. };
  5023. // Properties
  5024. /**
  5025. * Check if the current matrix is indentity
  5026. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5027. * @returns true is the matrix is the identity matrix
  5028. */
  5029. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5030. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5031. if (this._isIdentityDirty) {
  5032. this._isIdentityDirty = false;
  5033. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5034. this._isIdentity = false;
  5035. }
  5036. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5037. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5038. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5039. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5040. this._isIdentity = false;
  5041. }
  5042. else {
  5043. this._isIdentity = true;
  5044. }
  5045. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5046. this._isIdentity = false;
  5047. }
  5048. }
  5049. return this._isIdentity;
  5050. };
  5051. /**
  5052. * Gets the determinant of the matrix
  5053. * @returns the matrix determinant
  5054. */
  5055. Matrix.prototype.determinant = function () {
  5056. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5057. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5058. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5059. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5060. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5061. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5062. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5063. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5064. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5065. };
  5066. // Methods
  5067. /**
  5068. * Returns the matrix as a Float32Array
  5069. * @returns the matrix underlying array
  5070. */
  5071. Matrix.prototype.toArray = function () {
  5072. return this.m;
  5073. };
  5074. /**
  5075. * Returns the matrix as a Float32Array
  5076. * @returns the matrix underlying array.
  5077. */
  5078. Matrix.prototype.asArray = function () {
  5079. return this.toArray();
  5080. };
  5081. /**
  5082. * Inverts the current matrix in place
  5083. * @returns the current inverted matrix
  5084. */
  5085. Matrix.prototype.invert = function () {
  5086. this.invertToRef(this);
  5087. return this;
  5088. };
  5089. /**
  5090. * Sets all the matrix elements to zero
  5091. * @returns the current matrix
  5092. */
  5093. Matrix.prototype.reset = function () {
  5094. for (var index = 0; index < 16; index++) {
  5095. this.m[index] = 0.0;
  5096. }
  5097. this._markAsUpdated();
  5098. return this;
  5099. };
  5100. /**
  5101. * Adds the current matrix with a second one
  5102. * @param other defines the matrix to add
  5103. * @returns a new matrix as the addition of the current matrix and the given one
  5104. */
  5105. Matrix.prototype.add = function (other) {
  5106. var result = new Matrix();
  5107. this.addToRef(other, result);
  5108. return result;
  5109. };
  5110. /**
  5111. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5112. * @param other defines the matrix to add
  5113. * @param result defines the target matrix
  5114. * @returns the current matrix
  5115. */
  5116. Matrix.prototype.addToRef = function (other, result) {
  5117. for (var index = 0; index < 16; index++) {
  5118. result.m[index] = this.m[index] + other.m[index];
  5119. }
  5120. result._markAsUpdated();
  5121. return this;
  5122. };
  5123. /**
  5124. * Adds in place the given matrix to the current matrix
  5125. * @param other defines the second operand
  5126. * @returns the current updated matrix
  5127. */
  5128. Matrix.prototype.addToSelf = function (other) {
  5129. for (var index = 0; index < 16; index++) {
  5130. this.m[index] += other.m[index];
  5131. }
  5132. this._markAsUpdated();
  5133. return this;
  5134. };
  5135. /**
  5136. * Sets the given matrix to the current inverted Matrix
  5137. * @param other defines the target matrix
  5138. * @returns the unmodified current matrix
  5139. */
  5140. Matrix.prototype.invertToRef = function (other) {
  5141. var l1 = this.m[0];
  5142. var l2 = this.m[1];
  5143. var l3 = this.m[2];
  5144. var l4 = this.m[3];
  5145. var l5 = this.m[4];
  5146. var l6 = this.m[5];
  5147. var l7 = this.m[6];
  5148. var l8 = this.m[7];
  5149. var l9 = this.m[8];
  5150. var l10 = this.m[9];
  5151. var l11 = this.m[10];
  5152. var l12 = this.m[11];
  5153. var l13 = this.m[12];
  5154. var l14 = this.m[13];
  5155. var l15 = this.m[14];
  5156. var l16 = this.m[15];
  5157. var l17 = (l11 * l16) - (l12 * l15);
  5158. var l18 = (l10 * l16) - (l12 * l14);
  5159. var l19 = (l10 * l15) - (l11 * l14);
  5160. var l20 = (l9 * l16) - (l12 * l13);
  5161. var l21 = (l9 * l15) - (l11 * l13);
  5162. var l22 = (l9 * l14) - (l10 * l13);
  5163. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5164. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5165. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5166. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5167. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5168. var l28 = (l7 * l16) - (l8 * l15);
  5169. var l29 = (l6 * l16) - (l8 * l14);
  5170. var l30 = (l6 * l15) - (l7 * l14);
  5171. var l31 = (l5 * l16) - (l8 * l13);
  5172. var l32 = (l5 * l15) - (l7 * l13);
  5173. var l33 = (l5 * l14) - (l6 * l13);
  5174. var l34 = (l7 * l12) - (l8 * l11);
  5175. var l35 = (l6 * l12) - (l8 * l10);
  5176. var l36 = (l6 * l11) - (l7 * l10);
  5177. var l37 = (l5 * l12) - (l8 * l9);
  5178. var l38 = (l5 * l11) - (l7 * l9);
  5179. var l39 = (l5 * l10) - (l6 * l9);
  5180. other.m[0] = l23 * l27;
  5181. other.m[4] = l24 * l27;
  5182. other.m[8] = l25 * l27;
  5183. other.m[12] = l26 * l27;
  5184. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5185. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5186. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5187. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5188. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5189. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5190. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5191. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5192. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5193. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5194. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5195. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5196. other._markAsUpdated();
  5197. return this;
  5198. };
  5199. /**
  5200. * Inserts the translation vector (using 3 floats) in the current matrix
  5201. * @param x defines the 1st component of the translation
  5202. * @param y defines the 2nd component of the translation
  5203. * @param z defines the 3rd component of the translation
  5204. * @returns the current updated matrix
  5205. */
  5206. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5207. this.m[12] = x;
  5208. this.m[13] = y;
  5209. this.m[14] = z;
  5210. this._markAsUpdated();
  5211. return this;
  5212. };
  5213. /**
  5214. * Inserts the translation vector in the current matrix
  5215. * @param vector3 defines the translation to insert
  5216. * @returns the current updated matrix
  5217. */
  5218. Matrix.prototype.setTranslation = function (vector3) {
  5219. this.m[12] = vector3.x;
  5220. this.m[13] = vector3.y;
  5221. this.m[14] = vector3.z;
  5222. this._markAsUpdated();
  5223. return this;
  5224. };
  5225. /**
  5226. * Gets the translation value of the current matrix
  5227. * @returns a new Vector3 as the extracted translation from the matrix
  5228. */
  5229. Matrix.prototype.getTranslation = function () {
  5230. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5231. };
  5232. /**
  5233. * Fill a Vector3 with the extracted translation from the matrix
  5234. * @param result defines the Vector3 where to store the translation
  5235. * @returns the current matrix
  5236. */
  5237. Matrix.prototype.getTranslationToRef = function (result) {
  5238. result.x = this.m[12];
  5239. result.y = this.m[13];
  5240. result.z = this.m[14];
  5241. return this;
  5242. };
  5243. /**
  5244. * Remove rotation and scaling part from the matrix
  5245. * @returns the updated matrix
  5246. */
  5247. Matrix.prototype.removeRotationAndScaling = function () {
  5248. this.setRowFromFloats(0, 1, 0, 0, 0);
  5249. this.setRowFromFloats(1, 0, 1, 0, 0);
  5250. this.setRowFromFloats(2, 0, 0, 1, 0);
  5251. return this;
  5252. };
  5253. /**
  5254. * Multiply two matrices
  5255. * @param other defines the second operand
  5256. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5257. */
  5258. Matrix.prototype.multiply = function (other) {
  5259. var result = new Matrix();
  5260. this.multiplyToRef(other, result);
  5261. return result;
  5262. };
  5263. /**
  5264. * Copy the current matrix from the given one
  5265. * @param other defines the source matrix
  5266. * @returns the current updated matrix
  5267. */
  5268. Matrix.prototype.copyFrom = function (other) {
  5269. for (var index = 0; index < 16; index++) {
  5270. this.m[index] = other.m[index];
  5271. }
  5272. this._markAsUpdated();
  5273. return this;
  5274. };
  5275. /**
  5276. * Populates the given array from the starting index with the current matrix values
  5277. * @param array defines the target array
  5278. * @param offset defines the offset in the target array where to start storing values
  5279. * @returns the current matrix
  5280. */
  5281. Matrix.prototype.copyToArray = function (array, offset) {
  5282. if (offset === void 0) { offset = 0; }
  5283. for (var index = 0; index < 16; index++) {
  5284. array[offset + index] = this.m[index];
  5285. }
  5286. return this;
  5287. };
  5288. /**
  5289. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5290. * @param other defines the second operand
  5291. * @param result defines the matrix where to store the multiplication
  5292. * @returns the current matrix
  5293. */
  5294. Matrix.prototype.multiplyToRef = function (other, result) {
  5295. this.multiplyToArray(other, result.m, 0);
  5296. result._markAsUpdated();
  5297. return this;
  5298. };
  5299. /**
  5300. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5301. * @param other defines the second operand
  5302. * @param result defines the array where to store the multiplication
  5303. * @param offset defines the offset in the target array where to start storing values
  5304. * @returns the current matrix
  5305. */
  5306. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5307. var tm0 = this.m[0];
  5308. var tm1 = this.m[1];
  5309. var tm2 = this.m[2];
  5310. var tm3 = this.m[3];
  5311. var tm4 = this.m[4];
  5312. var tm5 = this.m[5];
  5313. var tm6 = this.m[6];
  5314. var tm7 = this.m[7];
  5315. var tm8 = this.m[8];
  5316. var tm9 = this.m[9];
  5317. var tm10 = this.m[10];
  5318. var tm11 = this.m[11];
  5319. var tm12 = this.m[12];
  5320. var tm13 = this.m[13];
  5321. var tm14 = this.m[14];
  5322. var tm15 = this.m[15];
  5323. var om0 = other.m[0];
  5324. var om1 = other.m[1];
  5325. var om2 = other.m[2];
  5326. var om3 = other.m[3];
  5327. var om4 = other.m[4];
  5328. var om5 = other.m[5];
  5329. var om6 = other.m[6];
  5330. var om7 = other.m[7];
  5331. var om8 = other.m[8];
  5332. var om9 = other.m[9];
  5333. var om10 = other.m[10];
  5334. var om11 = other.m[11];
  5335. var om12 = other.m[12];
  5336. var om13 = other.m[13];
  5337. var om14 = other.m[14];
  5338. var om15 = other.m[15];
  5339. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5340. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5341. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5342. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5343. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5344. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5345. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5346. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5347. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5348. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5349. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5350. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5351. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5352. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5353. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5354. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5355. return this;
  5356. };
  5357. /**
  5358. * Check equality between this matrix and a second one
  5359. * @param value defines the second matrix to compare
  5360. * @returns true is the current matrix and the given one values are strictly equal
  5361. */
  5362. Matrix.prototype.equals = function (value) {
  5363. return value &&
  5364. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5365. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5366. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5367. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5368. };
  5369. /**
  5370. * Clone the current matrix
  5371. * @returns a new matrix from the current matrix
  5372. */
  5373. Matrix.prototype.clone = function () {
  5374. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5375. };
  5376. /**
  5377. * Returns the name of the current matrix class
  5378. * @returns the string "Matrix"
  5379. */
  5380. Matrix.prototype.getClassName = function () {
  5381. return "Matrix";
  5382. };
  5383. /**
  5384. * Gets the hash code of the current matrix
  5385. * @returns the hash code
  5386. */
  5387. Matrix.prototype.getHashCode = function () {
  5388. var hash = this.m[0] || 0;
  5389. for (var i = 1; i < 16; i++) {
  5390. hash = (hash * 397) ^ (this.m[i] || 0);
  5391. }
  5392. return hash;
  5393. };
  5394. /**
  5395. * Decomposes the current Matrix into a translation, rotation and scaling components
  5396. * @param scale defines the scale vector3 given as a reference to update
  5397. * @param rotation defines the rotation quaternion given as a reference to update
  5398. * @param translation defines the translation vector3 given as a reference to update
  5399. * @returns true if operation was successful
  5400. */
  5401. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5402. if (translation) {
  5403. translation.x = this.m[12];
  5404. translation.y = this.m[13];
  5405. translation.z = this.m[14];
  5406. }
  5407. scale = scale || MathTmp.Vector3[0];
  5408. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5409. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5410. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5411. if (this.determinant() <= 0) {
  5412. scale.y *= -1;
  5413. }
  5414. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5415. if (rotation) {
  5416. rotation.x = 0;
  5417. rotation.y = 0;
  5418. rotation.z = 0;
  5419. rotation.w = 1;
  5420. }
  5421. return false;
  5422. }
  5423. if (rotation) {
  5424. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5425. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5426. }
  5427. return true;
  5428. };
  5429. /**
  5430. * Gets specific row of the matrix
  5431. * @param index defines the number of the row to get
  5432. * @returns the index-th row of the current matrix as a new Vector4
  5433. */
  5434. Matrix.prototype.getRow = function (index) {
  5435. if (index < 0 || index > 3) {
  5436. return null;
  5437. }
  5438. var i = index * 4;
  5439. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5440. };
  5441. /**
  5442. * Sets the index-th row of the current matrix to the vector4 values
  5443. * @param index defines the number of the row to set
  5444. * @param row defines the target vector4
  5445. * @returns the updated current matrix
  5446. */
  5447. Matrix.prototype.setRow = function (index, row) {
  5448. if (index < 0 || index > 3) {
  5449. return this;
  5450. }
  5451. var i = index * 4;
  5452. this.m[i + 0] = row.x;
  5453. this.m[i + 1] = row.y;
  5454. this.m[i + 2] = row.z;
  5455. this.m[i + 3] = row.w;
  5456. this._markAsUpdated();
  5457. return this;
  5458. };
  5459. /**
  5460. * Compute the transpose of the matrix
  5461. * @returns the new transposed matrix
  5462. */
  5463. Matrix.prototype.transpose = function () {
  5464. return Matrix.Transpose(this);
  5465. };
  5466. /**
  5467. * Compute the transpose of the matrix and store it in a given matrix
  5468. * @param result defines the target matrix
  5469. * @returns the current matrix
  5470. */
  5471. Matrix.prototype.transposeToRef = function (result) {
  5472. Matrix.TransposeToRef(this, result);
  5473. return this;
  5474. };
  5475. /**
  5476. * Sets the index-th row of the current matrix with the given 4 x float values
  5477. * @param index defines the row index
  5478. * @param x defines the x component to set
  5479. * @param y defines the y component to set
  5480. * @param z defines the z component to set
  5481. * @param w defines the w component to set
  5482. * @returns the updated current matrix
  5483. */
  5484. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5485. if (index < 0 || index > 3) {
  5486. return this;
  5487. }
  5488. var i = index * 4;
  5489. this.m[i + 0] = x;
  5490. this.m[i + 1] = y;
  5491. this.m[i + 2] = z;
  5492. this.m[i + 3] = w;
  5493. this._markAsUpdated();
  5494. return this;
  5495. };
  5496. /**
  5497. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5498. * @param scale defines the scale factor
  5499. * @returns a new matrix
  5500. */
  5501. Matrix.prototype.scale = function (scale) {
  5502. var result = new Matrix();
  5503. this.scaleToRef(scale, result);
  5504. return result;
  5505. };
  5506. /**
  5507. * Scale the current matrix values by a factor to a given result matrix
  5508. * @param scale defines the scale factor
  5509. * @param result defines the matrix to store the result
  5510. * @returns the current matrix
  5511. */
  5512. Matrix.prototype.scaleToRef = function (scale, result) {
  5513. for (var index = 0; index < 16; index++) {
  5514. result.m[index] = this.m[index] * scale;
  5515. }
  5516. result._markAsUpdated();
  5517. return this;
  5518. };
  5519. /**
  5520. * Scale the current matrix values by a factor and add the result to a given matrix
  5521. * @param scale defines the scale factor
  5522. * @param result defines the Matrix to store the result
  5523. * @returns the current matrix
  5524. */
  5525. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5526. for (var index = 0; index < 16; index++) {
  5527. result.m[index] += this.m[index] * scale;
  5528. }
  5529. result._markAsUpdated();
  5530. return this;
  5531. };
  5532. /**
  5533. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5534. * @param ref matrix to store the result
  5535. */
  5536. Matrix.prototype.toNormalMatrix = function (ref) {
  5537. this.invertToRef(ref);
  5538. ref.transpose();
  5539. var m = ref.m;
  5540. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5541. };
  5542. /**
  5543. * Gets only rotation part of the current matrix
  5544. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5545. */
  5546. Matrix.prototype.getRotationMatrix = function () {
  5547. var result = Matrix.Identity();
  5548. this.getRotationMatrixToRef(result);
  5549. return result;
  5550. };
  5551. /**
  5552. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5553. * @param result defines the target matrix to store data to
  5554. * @returns the current matrix
  5555. */
  5556. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5557. var m = this.m;
  5558. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5559. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5560. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5561. if (this.determinant() <= 0) {
  5562. sy *= -1;
  5563. }
  5564. if (sx === 0 || sy === 0 || sz === 0) {
  5565. Matrix.IdentityToRef(result);
  5566. }
  5567. else {
  5568. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5569. }
  5570. return this;
  5571. };
  5572. // Statics
  5573. /**
  5574. * Creates a matrix from an array
  5575. * @param array defines the source array
  5576. * @param offset defines an offset in the source array
  5577. * @returns a new Matrix set from the starting index of the given array
  5578. */
  5579. Matrix.FromArray = function (array, offset) {
  5580. var result = new Matrix();
  5581. if (!offset) {
  5582. offset = 0;
  5583. }
  5584. Matrix.FromArrayToRef(array, offset, result);
  5585. return result;
  5586. };
  5587. /**
  5588. * Copy the content of an array into a given matrix
  5589. * @param array defines the source array
  5590. * @param offset defines an offset in the source array
  5591. * @param result defines the target matrix
  5592. */
  5593. Matrix.FromArrayToRef = function (array, offset, result) {
  5594. for (var index = 0; index < 16; index++) {
  5595. result.m[index] = array[index + offset];
  5596. }
  5597. result._markAsUpdated();
  5598. };
  5599. /**
  5600. * Stores an array into a matrix after having multiplied each component by a given factor
  5601. * @param array defines the source array
  5602. * @param offset defines the offset in the source array
  5603. * @param scale defines the scaling factor
  5604. * @param result defines the target matrix
  5605. */
  5606. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5607. for (var index = 0; index < 16; index++) {
  5608. result.m[index] = array[index + offset] * scale;
  5609. }
  5610. result._markAsUpdated();
  5611. };
  5612. /**
  5613. * Stores a list of values (16) inside a given matrix
  5614. * @param initialM11 defines 1st value of 1st row
  5615. * @param initialM12 defines 2nd value of 1st row
  5616. * @param initialM13 defines 3rd value of 1st row
  5617. * @param initialM14 defines 4th value of 1st row
  5618. * @param initialM21 defines 1st value of 2nd row
  5619. * @param initialM22 defines 2nd value of 2nd row
  5620. * @param initialM23 defines 3rd value of 2nd row
  5621. * @param initialM24 defines 4th value of 2nd row
  5622. * @param initialM31 defines 1st value of 3rd row
  5623. * @param initialM32 defines 2nd value of 3rd row
  5624. * @param initialM33 defines 3rd value of 3rd row
  5625. * @param initialM34 defines 4th value of 3rd row
  5626. * @param initialM41 defines 1st value of 4th row
  5627. * @param initialM42 defines 2nd value of 4th row
  5628. * @param initialM43 defines 3rd value of 4th row
  5629. * @param initialM44 defines 4th value of 4th row
  5630. * @param result defines the target matrix
  5631. */
  5632. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5633. result.m[0] = initialM11;
  5634. result.m[1] = initialM12;
  5635. result.m[2] = initialM13;
  5636. result.m[3] = initialM14;
  5637. result.m[4] = initialM21;
  5638. result.m[5] = initialM22;
  5639. result.m[6] = initialM23;
  5640. result.m[7] = initialM24;
  5641. result.m[8] = initialM31;
  5642. result.m[9] = initialM32;
  5643. result.m[10] = initialM33;
  5644. result.m[11] = initialM34;
  5645. result.m[12] = initialM41;
  5646. result.m[13] = initialM42;
  5647. result.m[14] = initialM43;
  5648. result.m[15] = initialM44;
  5649. result._markAsUpdated();
  5650. };
  5651. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5652. /**
  5653. * Gets an identity matrix that must not be updated
  5654. */
  5655. get: function () {
  5656. return Matrix._identityReadOnly;
  5657. },
  5658. enumerable: true,
  5659. configurable: true
  5660. });
  5661. /**
  5662. * Creates new matrix from a list of values (16)
  5663. * @param initialM11 defines 1st value of 1st row
  5664. * @param initialM12 defines 2nd value of 1st row
  5665. * @param initialM13 defines 3rd value of 1st row
  5666. * @param initialM14 defines 4th value of 1st row
  5667. * @param initialM21 defines 1st value of 2nd row
  5668. * @param initialM22 defines 2nd value of 2nd row
  5669. * @param initialM23 defines 3rd value of 2nd row
  5670. * @param initialM24 defines 4th value of 2nd row
  5671. * @param initialM31 defines 1st value of 3rd row
  5672. * @param initialM32 defines 2nd value of 3rd row
  5673. * @param initialM33 defines 3rd value of 3rd row
  5674. * @param initialM34 defines 4th value of 3rd row
  5675. * @param initialM41 defines 1st value of 4th row
  5676. * @param initialM42 defines 2nd value of 4th row
  5677. * @param initialM43 defines 3rd value of 4th row
  5678. * @param initialM44 defines 4th value of 4th row
  5679. * @returns the new matrix
  5680. */
  5681. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5682. var result = new Matrix();
  5683. result.m[0] = initialM11;
  5684. result.m[1] = initialM12;
  5685. result.m[2] = initialM13;
  5686. result.m[3] = initialM14;
  5687. result.m[4] = initialM21;
  5688. result.m[5] = initialM22;
  5689. result.m[6] = initialM23;
  5690. result.m[7] = initialM24;
  5691. result.m[8] = initialM31;
  5692. result.m[9] = initialM32;
  5693. result.m[10] = initialM33;
  5694. result.m[11] = initialM34;
  5695. result.m[12] = initialM41;
  5696. result.m[13] = initialM42;
  5697. result.m[14] = initialM43;
  5698. result.m[15] = initialM44;
  5699. return result;
  5700. };
  5701. /**
  5702. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5703. * @param scale defines the scale vector3
  5704. * @param rotation defines the rotation quaternion
  5705. * @param translation defines the translation vector3
  5706. * @returns a new matrix
  5707. */
  5708. Matrix.Compose = function (scale, rotation, translation) {
  5709. var result = Matrix.Identity();
  5710. Matrix.ComposeToRef(scale, rotation, translation, result);
  5711. return result;
  5712. };
  5713. /**
  5714. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5715. * @param scale defines the scale vector3
  5716. * @param rotation defines the rotation quaternion
  5717. * @param translation defines the translation vector3
  5718. * @param result defines the target matrix
  5719. */
  5720. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5721. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5722. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5723. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5724. result.setTranslation(translation);
  5725. };
  5726. /**
  5727. * Creates a new identity matrix
  5728. * @returns a new identity matrix
  5729. */
  5730. Matrix.Identity = function () {
  5731. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5732. };
  5733. /**
  5734. * Creates a new identity matrix and stores the result in a given matrix
  5735. * @param result defines the target matrix
  5736. */
  5737. Matrix.IdentityToRef = function (result) {
  5738. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5739. };
  5740. /**
  5741. * Creates a new zero matrix
  5742. * @returns a new zero matrix
  5743. */
  5744. Matrix.Zero = function () {
  5745. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5746. };
  5747. /**
  5748. * Creates a new rotation matrix for "angle" radians around the X axis
  5749. * @param angle defines the angle (in radians) to use
  5750. * @return the new matrix
  5751. */
  5752. Matrix.RotationX = function (angle) {
  5753. var result = new Matrix();
  5754. Matrix.RotationXToRef(angle, result);
  5755. return result;
  5756. };
  5757. /**
  5758. * Creates a new matrix as the invert of a given matrix
  5759. * @param source defines the source matrix
  5760. * @returns the new matrix
  5761. */
  5762. Matrix.Invert = function (source) {
  5763. var result = new Matrix();
  5764. source.invertToRef(result);
  5765. return result;
  5766. };
  5767. /**
  5768. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5769. * @param angle defines the angle (in radians) to use
  5770. * @param result defines the target matrix
  5771. */
  5772. Matrix.RotationXToRef = function (angle, result) {
  5773. var s = Math.sin(angle);
  5774. var c = Math.cos(angle);
  5775. result.m[0] = 1.0;
  5776. result.m[15] = 1.0;
  5777. result.m[5] = c;
  5778. result.m[10] = c;
  5779. result.m[9] = -s;
  5780. result.m[6] = s;
  5781. result.m[1] = 0.0;
  5782. result.m[2] = 0.0;
  5783. result.m[3] = 0.0;
  5784. result.m[4] = 0.0;
  5785. result.m[7] = 0.0;
  5786. result.m[8] = 0.0;
  5787. result.m[11] = 0.0;
  5788. result.m[12] = 0.0;
  5789. result.m[13] = 0.0;
  5790. result.m[14] = 0.0;
  5791. result._markAsUpdated();
  5792. };
  5793. /**
  5794. * Creates a new rotation matrix for "angle" radians around the Y axis
  5795. * @param angle defines the angle (in radians) to use
  5796. * @return the new matrix
  5797. */
  5798. Matrix.RotationY = function (angle) {
  5799. var result = new Matrix();
  5800. Matrix.RotationYToRef(angle, result);
  5801. return result;
  5802. };
  5803. /**
  5804. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5805. * @param angle defines the angle (in radians) to use
  5806. * @param result defines the target matrix
  5807. */
  5808. Matrix.RotationYToRef = function (angle, result) {
  5809. var s = Math.sin(angle);
  5810. var c = Math.cos(angle);
  5811. result.m[5] = 1.0;
  5812. result.m[15] = 1.0;
  5813. result.m[0] = c;
  5814. result.m[2] = -s;
  5815. result.m[8] = s;
  5816. result.m[10] = c;
  5817. result.m[1] = 0.0;
  5818. result.m[3] = 0.0;
  5819. result.m[4] = 0.0;
  5820. result.m[6] = 0.0;
  5821. result.m[7] = 0.0;
  5822. result.m[9] = 0.0;
  5823. result.m[11] = 0.0;
  5824. result.m[12] = 0.0;
  5825. result.m[13] = 0.0;
  5826. result.m[14] = 0.0;
  5827. result._markAsUpdated();
  5828. };
  5829. /**
  5830. * Creates a new rotation matrix for "angle" radians around the Z axis
  5831. * @param angle defines the angle (in radians) to use
  5832. * @return the new matrix
  5833. */
  5834. Matrix.RotationZ = function (angle) {
  5835. var result = new Matrix();
  5836. Matrix.RotationZToRef(angle, result);
  5837. return result;
  5838. };
  5839. /**
  5840. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5841. * @param angle defines the angle (in radians) to use
  5842. * @param result defines the target matrix
  5843. */
  5844. Matrix.RotationZToRef = function (angle, result) {
  5845. var s = Math.sin(angle);
  5846. var c = Math.cos(angle);
  5847. result.m[10] = 1.0;
  5848. result.m[15] = 1.0;
  5849. result.m[0] = c;
  5850. result.m[1] = s;
  5851. result.m[4] = -s;
  5852. result.m[5] = c;
  5853. result.m[2] = 0.0;
  5854. result.m[3] = 0.0;
  5855. result.m[6] = 0.0;
  5856. result.m[7] = 0.0;
  5857. result.m[8] = 0.0;
  5858. result.m[9] = 0.0;
  5859. result.m[11] = 0.0;
  5860. result.m[12] = 0.0;
  5861. result.m[13] = 0.0;
  5862. result.m[14] = 0.0;
  5863. result._markAsUpdated();
  5864. };
  5865. /**
  5866. * Creates a new rotation matrix for "angle" radians around the given axis
  5867. * @param axis defines the axis to use
  5868. * @param angle defines the angle (in radians) to use
  5869. * @return the new matrix
  5870. */
  5871. Matrix.RotationAxis = function (axis, angle) {
  5872. var result = Matrix.Zero();
  5873. Matrix.RotationAxisToRef(axis, angle, result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5878. * @param axis defines the axis to use
  5879. * @param angle defines the angle (in radians) to use
  5880. * @param result defines the target matrix
  5881. */
  5882. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5883. var s = Math.sin(-angle);
  5884. var c = Math.cos(-angle);
  5885. var c1 = 1 - c;
  5886. axis.normalize();
  5887. result.m[0] = (axis.x * axis.x) * c1 + c;
  5888. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5889. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5890. result.m[3] = 0.0;
  5891. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5892. result.m[5] = (axis.y * axis.y) * c1 + c;
  5893. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5894. result.m[7] = 0.0;
  5895. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5896. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5897. result.m[10] = (axis.z * axis.z) * c1 + c;
  5898. result.m[11] = 0.0;
  5899. result.m[15] = 1.0;
  5900. result._markAsUpdated();
  5901. };
  5902. /**
  5903. * Creates a rotation matrix
  5904. * @param yaw defines the yaw angle in radians (Y axis)
  5905. * @param pitch defines the pitch angle in radians (X axis)
  5906. * @param roll defines the roll angle in radians (X axis)
  5907. * @returns the new rotation matrix
  5908. */
  5909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5910. var result = new Matrix();
  5911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5912. return result;
  5913. };
  5914. /**
  5915. * Creates a rotation matrix and stores it in a given matrix
  5916. * @param yaw defines the yaw angle in radians (Y axis)
  5917. * @param pitch defines the pitch angle in radians (X axis)
  5918. * @param roll defines the roll angle in radians (X axis)
  5919. * @param result defines the target matrix
  5920. */
  5921. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5922. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5923. this._tempQuaternion.toRotationMatrix(result);
  5924. };
  5925. /**
  5926. * Creates a scaling matrix
  5927. * @param x defines the scale factor on X axis
  5928. * @param y defines the scale factor on Y axis
  5929. * @param z defines the scale factor on Z axis
  5930. * @returns the new matrix
  5931. */
  5932. Matrix.Scaling = function (x, y, z) {
  5933. var result = Matrix.Zero();
  5934. Matrix.ScalingToRef(x, y, z, result);
  5935. return result;
  5936. };
  5937. /**
  5938. * Creates a scaling matrix and stores it in a given matrix
  5939. * @param x defines the scale factor on X axis
  5940. * @param y defines the scale factor on Y axis
  5941. * @param z defines the scale factor on Z axis
  5942. * @param result defines the target matrix
  5943. */
  5944. Matrix.ScalingToRef = function (x, y, z, result) {
  5945. result.m[0] = x;
  5946. result.m[1] = 0.0;
  5947. result.m[2] = 0.0;
  5948. result.m[3] = 0.0;
  5949. result.m[4] = 0.0;
  5950. result.m[5] = y;
  5951. result.m[6] = 0.0;
  5952. result.m[7] = 0.0;
  5953. result.m[8] = 0.0;
  5954. result.m[9] = 0.0;
  5955. result.m[10] = z;
  5956. result.m[11] = 0.0;
  5957. result.m[12] = 0.0;
  5958. result.m[13] = 0.0;
  5959. result.m[14] = 0.0;
  5960. result.m[15] = 1.0;
  5961. result._markAsUpdated();
  5962. };
  5963. /**
  5964. * Creates a translation matrix
  5965. * @param x defines the translation on X axis
  5966. * @param y defines the translation on Y axis
  5967. * @param z defines the translationon Z axis
  5968. * @returns the new matrix
  5969. */
  5970. Matrix.Translation = function (x, y, z) {
  5971. var result = Matrix.Identity();
  5972. Matrix.TranslationToRef(x, y, z, result);
  5973. return result;
  5974. };
  5975. /**
  5976. * Creates a translation matrix and stores it in a given matrix
  5977. * @param x defines the translation on X axis
  5978. * @param y defines the translation on Y axis
  5979. * @param z defines the translationon Z axis
  5980. * @param result defines the target matrix
  5981. */
  5982. Matrix.TranslationToRef = function (x, y, z, result) {
  5983. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  5984. };
  5985. /**
  5986. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5987. * @param startValue defines the start value
  5988. * @param endValue defines the end value
  5989. * @param gradient defines the gradient factor
  5990. * @returns the new matrix
  5991. */
  5992. Matrix.Lerp = function (startValue, endValue, gradient) {
  5993. var result = Matrix.Zero();
  5994. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5995. return result;
  5996. };
  5997. /**
  5998. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5999. * @param startValue defines the start value
  6000. * @param endValue defines the end value
  6001. * @param gradient defines the gradient factor
  6002. * @param result defines the Matrix object where to store data
  6003. */
  6004. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6005. for (var index = 0; index < 16; index++) {
  6006. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6007. }
  6008. result._markAsUpdated();
  6009. };
  6010. /**
  6011. * Builds a new matrix whose values are computed by:
  6012. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6013. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6014. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6015. * @param startValue defines the first matrix
  6016. * @param endValue defines the second matrix
  6017. * @param gradient defines the gradient between the two matrices
  6018. * @returns the new matrix
  6019. */
  6020. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6021. var result = Matrix.Zero();
  6022. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6023. return result;
  6024. };
  6025. /**
  6026. * Update a matrix to values which are computed by:
  6027. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6028. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6029. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6030. * @param startValue defines the first matrix
  6031. * @param endValue defines the second matrix
  6032. * @param gradient defines the gradient between the two matrices
  6033. * @param result defines the target matrix
  6034. */
  6035. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6036. var startScale = MathTmp.Vector3[0];
  6037. var startRotation = MathTmp.Quaternion[0];
  6038. var startTranslation = MathTmp.Vector3[1];
  6039. startValue.decompose(startScale, startRotation, startTranslation);
  6040. var endScale = MathTmp.Vector3[2];
  6041. var endRotation = MathTmp.Quaternion[1];
  6042. var endTranslation = MathTmp.Vector3[3];
  6043. endValue.decompose(endScale, endRotation, endTranslation);
  6044. var resultScale = MathTmp.Vector3[4];
  6045. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6046. var resultRotation = MathTmp.Quaternion[2];
  6047. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6048. var resultTranslation = MathTmp.Vector3[5];
  6049. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6050. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6051. };
  6052. /**
  6053. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6054. * This function works in left handed mode
  6055. * @param eye defines the final position of the entity
  6056. * @param target defines where the entity should look at
  6057. * @param up defines the up vector for the entity
  6058. * @returns the new matrix
  6059. */
  6060. Matrix.LookAtLH = function (eye, target, up) {
  6061. var result = Matrix.Zero();
  6062. Matrix.LookAtLHToRef(eye, target, up, result);
  6063. return result;
  6064. };
  6065. /**
  6066. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6067. * This function works in left handed mode
  6068. * @param eye defines the final position of the entity
  6069. * @param target defines where the entity should look at
  6070. * @param up defines the up vector for the entity
  6071. * @param result defines the target matrix
  6072. */
  6073. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6074. // Z axis
  6075. target.subtractToRef(eye, this._zAxis);
  6076. this._zAxis.normalize();
  6077. // X axis
  6078. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6079. if (this._xAxis.lengthSquared() === 0) {
  6080. this._xAxis.x = 1.0;
  6081. }
  6082. else {
  6083. this._xAxis.normalize();
  6084. }
  6085. // Y axis
  6086. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6087. this._yAxis.normalize();
  6088. // Eye angles
  6089. var ex = -Vector3.Dot(this._xAxis, eye);
  6090. var ey = -Vector3.Dot(this._yAxis, eye);
  6091. var ez = -Vector3.Dot(this._zAxis, eye);
  6092. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6093. };
  6094. /**
  6095. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6096. * This function works in right handed mode
  6097. * @param eye defines the final position of the entity
  6098. * @param target defines where the entity should look at
  6099. * @param up defines the up vector for the entity
  6100. * @returns the new matrix
  6101. */
  6102. Matrix.LookAtRH = function (eye, target, up) {
  6103. var result = Matrix.Zero();
  6104. Matrix.LookAtRHToRef(eye, target, up, result);
  6105. return result;
  6106. };
  6107. /**
  6108. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6109. * This function works in right handed mode
  6110. * @param eye defines the final position of the entity
  6111. * @param target defines where the entity should look at
  6112. * @param up defines the up vector for the entity
  6113. * @param result defines the target matrix
  6114. */
  6115. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6116. // Z axis
  6117. eye.subtractToRef(target, this._zAxis);
  6118. this._zAxis.normalize();
  6119. // X axis
  6120. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6121. if (this._xAxis.lengthSquared() === 0) {
  6122. this._xAxis.x = 1.0;
  6123. }
  6124. else {
  6125. this._xAxis.normalize();
  6126. }
  6127. // Y axis
  6128. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6129. this._yAxis.normalize();
  6130. // Eye angles
  6131. var ex = -Vector3.Dot(this._xAxis, eye);
  6132. var ey = -Vector3.Dot(this._yAxis, eye);
  6133. var ez = -Vector3.Dot(this._zAxis, eye);
  6134. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6135. };
  6136. /**
  6137. * Create a left-handed orthographic projection matrix
  6138. * @param width defines the viewport width
  6139. * @param height defines the viewport height
  6140. * @param znear defines the near clip plane
  6141. * @param zfar defines the far clip plane
  6142. * @returns a new matrix as a left-handed orthographic projection matrix
  6143. */
  6144. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6145. var matrix = Matrix.Zero();
  6146. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6147. return matrix;
  6148. };
  6149. /**
  6150. * Store a left-handed orthographic projection to a given matrix
  6151. * @param width defines the viewport width
  6152. * @param height defines the viewport height
  6153. * @param znear defines the near clip plane
  6154. * @param zfar defines the far clip plane
  6155. * @param result defines the target matrix
  6156. */
  6157. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6158. var n = znear;
  6159. var f = zfar;
  6160. var a = 2.0 / width;
  6161. var b = 2.0 / height;
  6162. var c = 2.0 / (f - n);
  6163. var d = -(f + n) / (f - n);
  6164. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  6165. };
  6166. /**
  6167. * Create a left-handed orthographic projection matrix
  6168. * @param left defines the viewport left coordinate
  6169. * @param right defines the viewport right coordinate
  6170. * @param bottom defines the viewport bottom coordinate
  6171. * @param top defines the viewport top coordinate
  6172. * @param znear defines the near clip plane
  6173. * @param zfar defines the far clip plane
  6174. * @returns a new matrix as a left-handed orthographic projection matrix
  6175. */
  6176. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6177. var matrix = Matrix.Zero();
  6178. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6179. return matrix;
  6180. };
  6181. /**
  6182. * Stores a left-handed orthographic projection into a given matrix
  6183. * @param left defines the viewport left coordinate
  6184. * @param right defines the viewport right coordinate
  6185. * @param bottom defines the viewport bottom coordinate
  6186. * @param top defines the viewport top coordinate
  6187. * @param znear defines the near clip plane
  6188. * @param zfar defines the far clip plane
  6189. * @param result defines the target matrix
  6190. */
  6191. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6192. var n = znear;
  6193. var f = zfar;
  6194. var a = 2.0 / (right - left);
  6195. var b = 2.0 / (top - bottom);
  6196. var c = 2.0 / (f - n);
  6197. var d = -(f + n) / (f - n);
  6198. var i0 = (left + right) / (left - right);
  6199. var i1 = (top + bottom) / (bottom - top);
  6200. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  6201. };
  6202. /**
  6203. * Creates a right-handed orthographic projection matrix
  6204. * @param left defines the viewport left coordinate
  6205. * @param right defines the viewport right coordinate
  6206. * @param bottom defines the viewport bottom coordinate
  6207. * @param top defines the viewport top coordinate
  6208. * @param znear defines the near clip plane
  6209. * @param zfar defines the far clip plane
  6210. * @returns a new matrix as a right-handed orthographic projection matrix
  6211. */
  6212. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6213. var matrix = Matrix.Zero();
  6214. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6215. return matrix;
  6216. };
  6217. /**
  6218. * Stores a right-handed orthographic projection into a given matrix
  6219. * @param left defines the viewport left coordinate
  6220. * @param right defines the viewport right coordinate
  6221. * @param bottom defines the viewport bottom coordinate
  6222. * @param top defines the viewport top coordinate
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @param result defines the target matrix
  6226. */
  6227. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6228. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6229. result.m[10] *= -1.0;
  6230. };
  6231. /**
  6232. * Creates a left-handed perspective projection matrix
  6233. * @param width defines the viewport width
  6234. * @param height defines the viewport height
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a left-handed perspective projection matrix
  6238. */
  6239. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. var n = znear;
  6242. var f = zfar;
  6243. var a = 2.0 * n / width;
  6244. var b = 2.0 * n / height;
  6245. var c = (f + n) / (f - n);
  6246. var d = -2.0 * f * n / (f - n);
  6247. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6248. return matrix;
  6249. };
  6250. /**
  6251. * Creates a left-handed perspective projection matrix
  6252. * @param fov defines the horizontal field of view
  6253. * @param aspect defines the aspect ratio
  6254. * @param znear defines the near clip plane
  6255. * @param zfar defines the far clip plane
  6256. * @returns a new matrix as a left-handed perspective projection matrix
  6257. */
  6258. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6259. var matrix = Matrix.Zero();
  6260. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6261. return matrix;
  6262. };
  6263. /**
  6264. * Stores a left-handed perspective projection into a given matrix
  6265. * @param fov defines the horizontal field of view
  6266. * @param aspect defines the aspect ratio
  6267. * @param znear defines the near clip plane
  6268. * @param zfar defines the far clip plane
  6269. * @param result defines the target matrix
  6270. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6271. */
  6272. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6273. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6274. var n = znear;
  6275. var f = zfar;
  6276. var t = 1.0 / (Math.tan(fov * 0.5));
  6277. var a = isVerticalFovFixed ? (t / aspect) : t;
  6278. var b = isVerticalFovFixed ? t : (t * aspect);
  6279. var c = (f + n) / (f - n);
  6280. var d = -2.0 * f * n / (f - n);
  6281. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  6282. };
  6283. /**
  6284. * Creates a right-handed perspective projection matrix
  6285. * @param fov defines the horizontal field of view
  6286. * @param aspect defines the aspect ratio
  6287. * @param znear defines the near clip plane
  6288. * @param zfar defines the far clip plane
  6289. * @returns a new matrix as a right-handed perspective projection matrix
  6290. */
  6291. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6292. var matrix = Matrix.Zero();
  6293. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6294. return matrix;
  6295. };
  6296. /**
  6297. * Stores a right-handed perspective projection into a given matrix
  6298. * @param fov defines the horizontal field of view
  6299. * @param aspect defines the aspect ratio
  6300. * @param znear defines the near clip plane
  6301. * @param zfar defines the far clip plane
  6302. * @param result defines the target matrix
  6303. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6304. */
  6305. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6306. //alternatively this could be expressed as:
  6307. // m = PerspectiveFovLHToRef
  6308. // m[10] *= -1.0;
  6309. // m[11] *= -1.0;
  6310. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6311. var n = znear;
  6312. var f = zfar;
  6313. var t = 1.0 / (Math.tan(fov * 0.5));
  6314. var a = isVerticalFovFixed ? (t / aspect) : t;
  6315. var b = isVerticalFovFixed ? t : (t * aspect);
  6316. var c = -(f + n) / (f - n);
  6317. var d = -2 * f * n / (f - n);
  6318. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  6319. };
  6320. /**
  6321. * Stores a perspective projection for WebVR info a given matrix
  6322. * @param fov defines the field of view
  6323. * @param znear defines the near clip plane
  6324. * @param zfar defines the far clip plane
  6325. * @param result defines the target matrix
  6326. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6327. */
  6328. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6329. if (rightHanded === void 0) { rightHanded = false; }
  6330. var rightHandedFactor = rightHanded ? -1 : 1;
  6331. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6332. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6333. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6334. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6335. var xScale = 2.0 / (leftTan + rightTan);
  6336. var yScale = 2.0 / (upTan + downTan);
  6337. result.m[0] = xScale;
  6338. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6339. result.m[5] = yScale;
  6340. result.m[6] = result.m[7] = 0.0;
  6341. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6342. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6343. result.m[10] = -zfar / (znear - zfar);
  6344. result.m[11] = 1.0 * rightHandedFactor;
  6345. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6346. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6347. result._markAsUpdated();
  6348. };
  6349. /**
  6350. * Computes a complete transformation matrix
  6351. * @param viewport defines the viewport to use
  6352. * @param world defines the world matrix
  6353. * @param view defines the view matrix
  6354. * @param projection defines the projection matrix
  6355. * @param zmin defines the near clip plane
  6356. * @param zmax defines the far clip plane
  6357. * @returns the transformation matrix
  6358. */
  6359. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6360. var cw = viewport.width;
  6361. var ch = viewport.height;
  6362. var cx = viewport.x;
  6363. var cy = viewport.y;
  6364. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  6365. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6366. };
  6367. /**
  6368. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6369. * @param matrix defines the matrix to use
  6370. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6371. */
  6372. Matrix.GetAsMatrix2x2 = function (matrix) {
  6373. return new Float32Array([
  6374. matrix.m[0], matrix.m[1],
  6375. matrix.m[4], matrix.m[5]
  6376. ]);
  6377. };
  6378. /**
  6379. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6380. * @param matrix defines the matrix to use
  6381. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6382. */
  6383. Matrix.GetAsMatrix3x3 = function (matrix) {
  6384. return new Float32Array([
  6385. matrix.m[0], matrix.m[1], matrix.m[2],
  6386. matrix.m[4], matrix.m[5], matrix.m[6],
  6387. matrix.m[8], matrix.m[9], matrix.m[10]
  6388. ]);
  6389. };
  6390. /**
  6391. * Compute the transpose of a given matrix
  6392. * @param matrix defines the matrix to transpose
  6393. * @returns the new matrix
  6394. */
  6395. Matrix.Transpose = function (matrix) {
  6396. var result = new Matrix();
  6397. Matrix.TransposeToRef(matrix, result);
  6398. return result;
  6399. };
  6400. /**
  6401. * Compute the transpose of a matrix and store it in a target matrix
  6402. * @param matrix defines the matrix to transpose
  6403. * @param result defines the target matrix
  6404. */
  6405. Matrix.TransposeToRef = function (matrix, result) {
  6406. result.m[0] = matrix.m[0];
  6407. result.m[1] = matrix.m[4];
  6408. result.m[2] = matrix.m[8];
  6409. result.m[3] = matrix.m[12];
  6410. result.m[4] = matrix.m[1];
  6411. result.m[5] = matrix.m[5];
  6412. result.m[6] = matrix.m[9];
  6413. result.m[7] = matrix.m[13];
  6414. result.m[8] = matrix.m[2];
  6415. result.m[9] = matrix.m[6];
  6416. result.m[10] = matrix.m[10];
  6417. result.m[11] = matrix.m[14];
  6418. result.m[12] = matrix.m[3];
  6419. result.m[13] = matrix.m[7];
  6420. result.m[14] = matrix.m[11];
  6421. result.m[15] = matrix.m[15];
  6422. };
  6423. /**
  6424. * Computes a reflection matrix from a plane
  6425. * @param plane defines the reflection plane
  6426. * @returns a new matrix
  6427. */
  6428. Matrix.Reflection = function (plane) {
  6429. var matrix = new Matrix();
  6430. Matrix.ReflectionToRef(plane, matrix);
  6431. return matrix;
  6432. };
  6433. /**
  6434. * Computes a reflection matrix from a plane
  6435. * @param plane defines the reflection plane
  6436. * @param result defines the target matrix
  6437. */
  6438. Matrix.ReflectionToRef = function (plane, result) {
  6439. plane.normalize();
  6440. var x = plane.normal.x;
  6441. var y = plane.normal.y;
  6442. var z = plane.normal.z;
  6443. var temp = -2 * x;
  6444. var temp2 = -2 * y;
  6445. var temp3 = -2 * z;
  6446. result.m[0] = (temp * x) + 1;
  6447. result.m[1] = temp2 * x;
  6448. result.m[2] = temp3 * x;
  6449. result.m[3] = 0.0;
  6450. result.m[4] = temp * y;
  6451. result.m[5] = (temp2 * y) + 1;
  6452. result.m[6] = temp3 * y;
  6453. result.m[7] = 0.0;
  6454. result.m[8] = temp * z;
  6455. result.m[9] = temp2 * z;
  6456. result.m[10] = (temp3 * z) + 1;
  6457. result.m[11] = 0.0;
  6458. result.m[12] = temp * plane.d;
  6459. result.m[13] = temp2 * plane.d;
  6460. result.m[14] = temp3 * plane.d;
  6461. result.m[15] = 1.0;
  6462. result._markAsUpdated();
  6463. };
  6464. /**
  6465. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6466. * @param xaxis defines the value of the 1st axis
  6467. * @param yaxis defines the value of the 2nd axis
  6468. * @param zaxis defines the value of the 3rd axis
  6469. * @param result defines the target matrix
  6470. */
  6471. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6472. result.m[0] = xaxis.x;
  6473. result.m[1] = xaxis.y;
  6474. result.m[2] = xaxis.z;
  6475. result.m[3] = 0.0;
  6476. result.m[4] = yaxis.x;
  6477. result.m[5] = yaxis.y;
  6478. result.m[6] = yaxis.z;
  6479. result.m[7] = 0.0;
  6480. result.m[8] = zaxis.x;
  6481. result.m[9] = zaxis.y;
  6482. result.m[10] = zaxis.z;
  6483. result.m[11] = 0.0;
  6484. result.m[12] = 0.0;
  6485. result.m[13] = 0.0;
  6486. result.m[14] = 0.0;
  6487. result.m[15] = 1.0;
  6488. result._markAsUpdated();
  6489. };
  6490. /**
  6491. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6492. * @param quat defines the quaternion to use
  6493. * @param result defines the target matrix
  6494. */
  6495. Matrix.FromQuaternionToRef = function (quat, result) {
  6496. var xx = quat.x * quat.x;
  6497. var yy = quat.y * quat.y;
  6498. var zz = quat.z * quat.z;
  6499. var xy = quat.x * quat.y;
  6500. var zw = quat.z * quat.w;
  6501. var zx = quat.z * quat.x;
  6502. var yw = quat.y * quat.w;
  6503. var yz = quat.y * quat.z;
  6504. var xw = quat.x * quat.w;
  6505. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6506. result.m[1] = 2.0 * (xy + zw);
  6507. result.m[2] = 2.0 * (zx - yw);
  6508. result.m[3] = 0.0;
  6509. result.m[4] = 2.0 * (xy - zw);
  6510. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6511. result.m[6] = 2.0 * (yz + xw);
  6512. result.m[7] = 0.0;
  6513. result.m[8] = 2.0 * (zx + yw);
  6514. result.m[9] = 2.0 * (yz - xw);
  6515. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6516. result.m[11] = 0.0;
  6517. result.m[12] = 0.0;
  6518. result.m[13] = 0.0;
  6519. result.m[14] = 0.0;
  6520. result.m[15] = 1.0;
  6521. result._markAsUpdated();
  6522. };
  6523. Matrix._tempQuaternion = new Quaternion();
  6524. Matrix._xAxis = Vector3.Zero();
  6525. Matrix._yAxis = Vector3.Zero();
  6526. Matrix._zAxis = Vector3.Zero();
  6527. Matrix._updateFlagSeed = 0;
  6528. Matrix._identityReadOnly = Matrix.Identity();
  6529. return Matrix;
  6530. }());
  6531. BABYLON.Matrix = Matrix;
  6532. var Plane = /** @class */ (function () {
  6533. /**
  6534. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6535. */
  6536. function Plane(a, b, c, d) {
  6537. this.normal = new Vector3(a, b, c);
  6538. this.d = d;
  6539. }
  6540. /**
  6541. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6542. */
  6543. Plane.prototype.asArray = function () {
  6544. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6545. };
  6546. // Methods
  6547. /**
  6548. * Returns a new plane copied from the current Plane.
  6549. */
  6550. Plane.prototype.clone = function () {
  6551. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6552. };
  6553. /**
  6554. * Returns the string "Plane".
  6555. */
  6556. Plane.prototype.getClassName = function () {
  6557. return "Plane";
  6558. };
  6559. /**
  6560. * Returns the Plane hash code.
  6561. */
  6562. Plane.prototype.getHashCode = function () {
  6563. var hash = this.normal.getHashCode();
  6564. hash = (hash * 397) ^ (this.d || 0);
  6565. return hash;
  6566. };
  6567. /**
  6568. * Normalize the current Plane in place.
  6569. * Returns the updated Plane.
  6570. */
  6571. Plane.prototype.normalize = function () {
  6572. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6573. var magnitude = 0.0;
  6574. if (norm !== 0) {
  6575. magnitude = 1.0 / norm;
  6576. }
  6577. this.normal.x *= magnitude;
  6578. this.normal.y *= magnitude;
  6579. this.normal.z *= magnitude;
  6580. this.d *= magnitude;
  6581. return this;
  6582. };
  6583. /**
  6584. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6585. */
  6586. Plane.prototype.transform = function (transformation) {
  6587. var transposedMatrix = Matrix.Transpose(transformation);
  6588. var x = this.normal.x;
  6589. var y = this.normal.y;
  6590. var z = this.normal.z;
  6591. var d = this.d;
  6592. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6593. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6594. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6595. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6596. return new Plane(normalX, normalY, normalZ, finalD);
  6597. };
  6598. /**
  6599. * Returns the dot product (float) of the point coordinates and the plane normal.
  6600. */
  6601. Plane.prototype.dotCoordinate = function (point) {
  6602. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6603. };
  6604. /**
  6605. * Updates the current Plane from the plane defined by the three given points.
  6606. * Returns the updated Plane.
  6607. */
  6608. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6609. var x1 = point2.x - point1.x;
  6610. var y1 = point2.y - point1.y;
  6611. var z1 = point2.z - point1.z;
  6612. var x2 = point3.x - point1.x;
  6613. var y2 = point3.y - point1.y;
  6614. var z2 = point3.z - point1.z;
  6615. var yz = (y1 * z2) - (z1 * y2);
  6616. var xz = (z1 * x2) - (x1 * z2);
  6617. var xy = (x1 * y2) - (y1 * x2);
  6618. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6619. var invPyth;
  6620. if (pyth !== 0) {
  6621. invPyth = 1.0 / pyth;
  6622. }
  6623. else {
  6624. invPyth = 0.0;
  6625. }
  6626. this.normal.x = yz * invPyth;
  6627. this.normal.y = xz * invPyth;
  6628. this.normal.z = xy * invPyth;
  6629. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6630. return this;
  6631. };
  6632. /**
  6633. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6634. */
  6635. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6636. var dot = Vector3.Dot(this.normal, direction);
  6637. return (dot <= epsilon);
  6638. };
  6639. /**
  6640. * Returns the signed distance (float) from the given point to the Plane.
  6641. */
  6642. Plane.prototype.signedDistanceTo = function (point) {
  6643. return Vector3.Dot(point, this.normal) + this.d;
  6644. };
  6645. // Statics
  6646. /**
  6647. * Returns a new Plane from the given array.
  6648. */
  6649. Plane.FromArray = function (array) {
  6650. return new Plane(array[0], array[1], array[2], array[3]);
  6651. };
  6652. /**
  6653. * Returns a new Plane defined by the three given points.
  6654. */
  6655. Plane.FromPoints = function (point1, point2, point3) {
  6656. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6657. result.copyFromPoints(point1, point2, point3);
  6658. return result;
  6659. };
  6660. /**
  6661. * Returns a new Plane the normal vector to this plane at the given origin point.
  6662. * Note : the vector "normal" is updated because normalized.
  6663. */
  6664. Plane.FromPositionAndNormal = function (origin, normal) {
  6665. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6666. normal.normalize();
  6667. result.normal = normal;
  6668. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6669. return result;
  6670. };
  6671. /**
  6672. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6673. */
  6674. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6675. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6676. return Vector3.Dot(point, normal) + d;
  6677. };
  6678. return Plane;
  6679. }());
  6680. BABYLON.Plane = Plane;
  6681. var Viewport = /** @class */ (function () {
  6682. /**
  6683. * Creates a Viewport object located at (x, y) and sized (width, height).
  6684. */
  6685. function Viewport(x, y, width, height) {
  6686. this.x = x;
  6687. this.y = y;
  6688. this.width = width;
  6689. this.height = height;
  6690. }
  6691. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6692. if (renderWidthOrEngine.getRenderWidth) {
  6693. var engine = renderWidthOrEngine;
  6694. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6695. }
  6696. var renderWidth = renderWidthOrEngine;
  6697. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6698. };
  6699. /**
  6700. * Returns a new Viewport copied from the current one.
  6701. */
  6702. Viewport.prototype.clone = function () {
  6703. return new Viewport(this.x, this.y, this.width, this.height);
  6704. };
  6705. return Viewport;
  6706. }());
  6707. BABYLON.Viewport = Viewport;
  6708. var Frustum = /** @class */ (function () {
  6709. function Frustum() {
  6710. }
  6711. /**
  6712. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6713. */
  6714. Frustum.GetPlanes = function (transform) {
  6715. var frustumPlanes = [];
  6716. for (var index = 0; index < 6; index++) {
  6717. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6718. }
  6719. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6720. return frustumPlanes;
  6721. };
  6722. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6723. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6724. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6725. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6726. frustumPlane.d = transform.m[15] + transform.m[14];
  6727. frustumPlane.normalize();
  6728. };
  6729. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6730. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6731. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6732. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6733. frustumPlane.d = transform.m[15] - transform.m[14];
  6734. frustumPlane.normalize();
  6735. };
  6736. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6737. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6738. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6739. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6740. frustumPlane.d = transform.m[15] + transform.m[12];
  6741. frustumPlane.normalize();
  6742. };
  6743. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6744. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6745. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6746. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6747. frustumPlane.d = transform.m[15] - transform.m[12];
  6748. frustumPlane.normalize();
  6749. };
  6750. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6751. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6752. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6753. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6754. frustumPlane.d = transform.m[15] - transform.m[13];
  6755. frustumPlane.normalize();
  6756. };
  6757. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6758. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6759. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6760. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6761. frustumPlane.d = transform.m[15] + transform.m[13];
  6762. frustumPlane.normalize();
  6763. };
  6764. /**
  6765. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6766. */
  6767. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6768. // Near
  6769. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6770. // Far
  6771. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6772. // Left
  6773. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6774. // Right
  6775. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6776. // Top
  6777. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6778. // Bottom
  6779. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6780. };
  6781. return Frustum;
  6782. }());
  6783. BABYLON.Frustum = Frustum;
  6784. /** Defines supported spaces */
  6785. var Space;
  6786. (function (Space) {
  6787. /** Local (object) space */
  6788. Space[Space["LOCAL"] = 0] = "LOCAL";
  6789. /** World space */
  6790. Space[Space["WORLD"] = 1] = "WORLD";
  6791. /** Bone space */
  6792. Space[Space["BONE"] = 2] = "BONE";
  6793. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6794. /** Defines the 3 main axes */
  6795. var Axis = /** @class */ (function () {
  6796. function Axis() {
  6797. }
  6798. /** X axis */
  6799. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6800. /** Y axis */
  6801. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6802. /** Z axis */
  6803. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6804. return Axis;
  6805. }());
  6806. BABYLON.Axis = Axis;
  6807. ;
  6808. var BezierCurve = /** @class */ (function () {
  6809. function BezierCurve() {
  6810. }
  6811. /**
  6812. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6813. */
  6814. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6815. // Extract X (which is equal to time here)
  6816. var f0 = 1 - 3 * x2 + 3 * x1;
  6817. var f1 = 3 * x2 - 6 * x1;
  6818. var f2 = 3 * x1;
  6819. var refinedT = t;
  6820. for (var i = 0; i < 5; i++) {
  6821. var refinedT2 = refinedT * refinedT;
  6822. var refinedT3 = refinedT2 * refinedT;
  6823. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6824. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6825. refinedT -= (x - t) * slope;
  6826. refinedT = Math.min(1, Math.max(0, refinedT));
  6827. }
  6828. // Resolve cubic bezier for the given x
  6829. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6830. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6831. Math.pow(refinedT, 3);
  6832. };
  6833. return BezierCurve;
  6834. }());
  6835. BABYLON.BezierCurve = BezierCurve;
  6836. /**
  6837. * Defines potential orientation for back face culling
  6838. */
  6839. var Orientation;
  6840. (function (Orientation) {
  6841. /**
  6842. * Clockwise
  6843. */
  6844. Orientation[Orientation["CW"] = 0] = "CW";
  6845. /** Counter clockwise */
  6846. Orientation[Orientation["CCW"] = 1] = "CCW";
  6847. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6848. /**
  6849. * Defines angle representation
  6850. */
  6851. var Angle = /** @class */ (function () {
  6852. /**
  6853. * Creates an Angle object of "radians" radians (float).
  6854. */
  6855. function Angle(radians) {
  6856. this._radians = radians;
  6857. if (this._radians < 0.0)
  6858. this._radians += (2.0 * Math.PI);
  6859. }
  6860. /**
  6861. * Get value in degrees
  6862. * @returns the Angle value in degrees (float)
  6863. */
  6864. Angle.prototype.degrees = function () {
  6865. return this._radians * 180.0 / Math.PI;
  6866. };
  6867. /**
  6868. * Get value in radians
  6869. * @returns the Angle value in radians (float)
  6870. */
  6871. Angle.prototype.radians = function () {
  6872. return this._radians;
  6873. };
  6874. /**
  6875. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6876. * @param a defines first vector
  6877. * @param b defines second vector
  6878. * @returns a new Angle
  6879. */
  6880. Angle.BetweenTwoPoints = function (a, b) {
  6881. var delta = b.subtract(a);
  6882. var theta = Math.atan2(delta.y, delta.x);
  6883. return new Angle(theta);
  6884. };
  6885. /**
  6886. * Gets a new Angle object from the given float in radians
  6887. * @param radians defines the angle value in radians
  6888. * @returns a new Angle
  6889. */
  6890. Angle.FromRadians = function (radians) {
  6891. return new Angle(radians);
  6892. };
  6893. /**
  6894. * Gets a new Angle object from the given float in degrees
  6895. * @param degrees defines the angle value in degrees
  6896. * @returns a new Angle
  6897. */
  6898. Angle.FromDegrees = function (degrees) {
  6899. return new Angle(degrees * Math.PI / 180.0);
  6900. };
  6901. return Angle;
  6902. }());
  6903. BABYLON.Angle = Angle;
  6904. var Arc2 = /** @class */ (function () {
  6905. /**
  6906. * Creates an Arc object from the three given points : start, middle and end.
  6907. */
  6908. function Arc2(startPoint, midPoint, endPoint) {
  6909. this.startPoint = startPoint;
  6910. this.midPoint = midPoint;
  6911. this.endPoint = endPoint;
  6912. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6913. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6914. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6915. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6916. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  6917. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6918. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6919. var a1 = this.startAngle.degrees();
  6920. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6921. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6922. // angles correction
  6923. if (a2 - a1 > +180.0)
  6924. a2 -= 360.0;
  6925. if (a2 - a1 < -180.0)
  6926. a2 += 360.0;
  6927. if (a3 - a2 > +180.0)
  6928. a3 -= 360.0;
  6929. if (a3 - a2 < -180.0)
  6930. a3 += 360.0;
  6931. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6932. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6933. }
  6934. return Arc2;
  6935. }());
  6936. BABYLON.Arc2 = Arc2;
  6937. var Path2 = /** @class */ (function () {
  6938. /**
  6939. * Creates a Path2 object from the starting 2D coordinates x and y.
  6940. */
  6941. function Path2(x, y) {
  6942. this._points = new Array();
  6943. this._length = 0.0;
  6944. this.closed = false;
  6945. this._points.push(new Vector2(x, y));
  6946. }
  6947. /**
  6948. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6949. * Returns the updated Path2.
  6950. */
  6951. Path2.prototype.addLineTo = function (x, y) {
  6952. if (this.closed) {
  6953. return this;
  6954. }
  6955. var newPoint = new Vector2(x, y);
  6956. var previousPoint = this._points[this._points.length - 1];
  6957. this._points.push(newPoint);
  6958. this._length += newPoint.subtract(previousPoint).length();
  6959. return this;
  6960. };
  6961. /**
  6962. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  6963. * Returns the updated Path2.
  6964. */
  6965. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6966. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6967. if (this.closed) {
  6968. return this;
  6969. }
  6970. var startPoint = this._points[this._points.length - 1];
  6971. var midPoint = new Vector2(midX, midY);
  6972. var endPoint = new Vector2(endX, endY);
  6973. var arc = new Arc2(startPoint, midPoint, endPoint);
  6974. var increment = arc.angle.radians() / numberOfSegments;
  6975. if (arc.orientation === Orientation.CW)
  6976. increment *= -1;
  6977. var currentAngle = arc.startAngle.radians() + increment;
  6978. for (var i = 0; i < numberOfSegments; i++) {
  6979. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6980. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6981. this.addLineTo(x, y);
  6982. currentAngle += increment;
  6983. }
  6984. return this;
  6985. };
  6986. /**
  6987. * Closes the Path2.
  6988. * Returns the Path2.
  6989. */
  6990. Path2.prototype.close = function () {
  6991. this.closed = true;
  6992. return this;
  6993. };
  6994. /**
  6995. * Returns the Path2 total length (float).
  6996. */
  6997. Path2.prototype.length = function () {
  6998. var result = this._length;
  6999. if (!this.closed) {
  7000. var lastPoint = this._points[this._points.length - 1];
  7001. var firstPoint = this._points[0];
  7002. result += (firstPoint.subtract(lastPoint).length());
  7003. }
  7004. return result;
  7005. };
  7006. /**
  7007. * Returns the Path2 internal array of points.
  7008. */
  7009. Path2.prototype.getPoints = function () {
  7010. return this._points;
  7011. };
  7012. /**
  7013. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7014. */
  7015. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7016. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7017. return Vector2.Zero();
  7018. }
  7019. var lengthPosition = normalizedLengthPosition * this.length();
  7020. var previousOffset = 0;
  7021. for (var i = 0; i < this._points.length; i++) {
  7022. var j = (i + 1) % this._points.length;
  7023. var a = this._points[i];
  7024. var b = this._points[j];
  7025. var bToA = b.subtract(a);
  7026. var nextOffset = (bToA.length() + previousOffset);
  7027. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7028. var dir = bToA.normalize();
  7029. var localOffset = lengthPosition - previousOffset;
  7030. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7031. }
  7032. previousOffset = nextOffset;
  7033. }
  7034. return Vector2.Zero();
  7035. };
  7036. /**
  7037. * Returns a new Path2 starting at the coordinates (x, y).
  7038. */
  7039. Path2.StartingAt = function (x, y) {
  7040. return new Path2(x, y);
  7041. };
  7042. return Path2;
  7043. }());
  7044. BABYLON.Path2 = Path2;
  7045. var Path3D = /** @class */ (function () {
  7046. /**
  7047. * new Path3D(path, normal, raw)
  7048. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7049. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7050. * path : an array of Vector3, the curve axis of the Path3D
  7051. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7052. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7053. */
  7054. function Path3D(path, firstNormal, raw) {
  7055. if (firstNormal === void 0) { firstNormal = null; }
  7056. this.path = path;
  7057. this._curve = new Array();
  7058. this._distances = new Array();
  7059. this._tangents = new Array();
  7060. this._normals = new Array();
  7061. this._binormals = new Array();
  7062. for (var p = 0; p < path.length; p++) {
  7063. this._curve[p] = path[p].clone(); // hard copy
  7064. }
  7065. this._raw = raw || false;
  7066. this._compute(firstNormal);
  7067. }
  7068. /**
  7069. * Returns the Path3D array of successive Vector3 designing its curve.
  7070. */
  7071. Path3D.prototype.getCurve = function () {
  7072. return this._curve;
  7073. };
  7074. /**
  7075. * Returns an array populated with tangent vectors on each Path3D curve point.
  7076. */
  7077. Path3D.prototype.getTangents = function () {
  7078. return this._tangents;
  7079. };
  7080. /**
  7081. * Returns an array populated with normal vectors on each Path3D curve point.
  7082. */
  7083. Path3D.prototype.getNormals = function () {
  7084. return this._normals;
  7085. };
  7086. /**
  7087. * Returns an array populated with binormal vectors on each Path3D curve point.
  7088. */
  7089. Path3D.prototype.getBinormals = function () {
  7090. return this._binormals;
  7091. };
  7092. /**
  7093. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7094. */
  7095. Path3D.prototype.getDistances = function () {
  7096. return this._distances;
  7097. };
  7098. /**
  7099. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7100. * Returns the same object updated.
  7101. */
  7102. Path3D.prototype.update = function (path, firstNormal) {
  7103. if (firstNormal === void 0) { firstNormal = null; }
  7104. for (var p = 0; p < path.length; p++) {
  7105. this._curve[p].x = path[p].x;
  7106. this._curve[p].y = path[p].y;
  7107. this._curve[p].z = path[p].z;
  7108. }
  7109. this._compute(firstNormal);
  7110. return this;
  7111. };
  7112. // private function compute() : computes tangents, normals and binormals
  7113. Path3D.prototype._compute = function (firstNormal) {
  7114. var l = this._curve.length;
  7115. // first and last tangents
  7116. this._tangents[0] = this._getFirstNonNullVector(0);
  7117. if (!this._raw) {
  7118. this._tangents[0].normalize();
  7119. }
  7120. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7121. if (!this._raw) {
  7122. this._tangents[l - 1].normalize();
  7123. }
  7124. // normals and binormals at first point : arbitrary vector with _normalVector()
  7125. var tg0 = this._tangents[0];
  7126. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7127. this._normals[0] = pp0;
  7128. if (!this._raw) {
  7129. this._normals[0].normalize();
  7130. }
  7131. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7132. if (!this._raw) {
  7133. this._binormals[0].normalize();
  7134. }
  7135. this._distances[0] = 0.0;
  7136. // normals and binormals : next points
  7137. var prev; // previous vector (segment)
  7138. var cur; // current vector (segment)
  7139. var curTang; // current tangent
  7140. // previous normal
  7141. var prevBinor; // previous binormal
  7142. for (var i = 1; i < l; i++) {
  7143. // tangents
  7144. prev = this._getLastNonNullVector(i);
  7145. if (i < l - 1) {
  7146. cur = this._getFirstNonNullVector(i);
  7147. this._tangents[i] = prev.add(cur);
  7148. this._tangents[i].normalize();
  7149. }
  7150. this._distances[i] = this._distances[i - 1] + prev.length();
  7151. // normals and binormals
  7152. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7153. curTang = this._tangents[i];
  7154. prevBinor = this._binormals[i - 1];
  7155. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7156. if (!this._raw) {
  7157. this._normals[i].normalize();
  7158. }
  7159. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7160. if (!this._raw) {
  7161. this._binormals[i].normalize();
  7162. }
  7163. }
  7164. };
  7165. // private function getFirstNonNullVector(index)
  7166. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7167. Path3D.prototype._getFirstNonNullVector = function (index) {
  7168. var i = 1;
  7169. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7170. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7171. i++;
  7172. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7173. }
  7174. return nNVector;
  7175. };
  7176. // private function getLastNonNullVector(index)
  7177. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7178. Path3D.prototype._getLastNonNullVector = function (index) {
  7179. var i = 1;
  7180. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7181. while (nLVector.length() === 0 && index > i + 1) {
  7182. i++;
  7183. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7184. }
  7185. return nLVector;
  7186. };
  7187. // private function normalVector(v0, vt, va) :
  7188. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7189. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7190. Path3D.prototype._normalVector = function (v0, vt, va) {
  7191. var normal0;
  7192. var tgl = vt.length();
  7193. if (tgl === 0.0) {
  7194. tgl = 1.0;
  7195. }
  7196. if (va === undefined || va === null) {
  7197. var point;
  7198. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7199. point = new Vector3(0.0, -1.0, 0.0);
  7200. }
  7201. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7202. point = new Vector3(1.0, 0.0, 0.0);
  7203. }
  7204. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7205. point = new Vector3(0.0, 0.0, 1.0);
  7206. }
  7207. else {
  7208. point = Vector3.Zero();
  7209. }
  7210. normal0 = Vector3.Cross(vt, point);
  7211. }
  7212. else {
  7213. normal0 = Vector3.Cross(vt, va);
  7214. Vector3.CrossToRef(normal0, vt, normal0);
  7215. }
  7216. normal0.normalize();
  7217. return normal0;
  7218. };
  7219. return Path3D;
  7220. }());
  7221. BABYLON.Path3D = Path3D;
  7222. var Curve3 = /** @class */ (function () {
  7223. /**
  7224. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7225. * A Curve3 is designed from a series of successive Vector3.
  7226. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7227. */
  7228. function Curve3(points) {
  7229. this._length = 0.0;
  7230. this._points = points;
  7231. this._length = this._computeLength(points);
  7232. }
  7233. /**
  7234. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7235. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7236. * @param v1 (Vector3) the control point
  7237. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7238. * @param nbPoints (integer) the wanted number of points in the curve
  7239. */
  7240. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7241. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7242. var bez = new Array();
  7243. var equation = function (t, val0, val1, val2) {
  7244. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7245. return res;
  7246. };
  7247. for (var i = 0; i <= nbPoints; i++) {
  7248. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  7249. }
  7250. return new Curve3(bez);
  7251. };
  7252. /**
  7253. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7254. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7255. * @param v1 (Vector3) the first control point
  7256. * @param v2 (Vector3) the second control point
  7257. * @param v3 (Vector3) the end point of the Cubic Bezier
  7258. * @param nbPoints (integer) the wanted number of points in the curve
  7259. */
  7260. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7261. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7262. var bez = new Array();
  7263. var equation = function (t, val0, val1, val2, val3) {
  7264. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  7265. return res;
  7266. };
  7267. for (var i = 0; i <= nbPoints; i++) {
  7268. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  7269. }
  7270. return new Curve3(bez);
  7271. };
  7272. /**
  7273. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7274. * @param p1 (Vector3) the origin point of the Hermite Spline
  7275. * @param t1 (Vector3) the tangent vector at the origin point
  7276. * @param p2 (Vector3) the end point of the Hermite Spline
  7277. * @param t2 (Vector3) the tangent vector at the end point
  7278. * @param nbPoints (integer) the wanted number of points in the curve
  7279. */
  7280. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7281. var hermite = new Array();
  7282. var step = 1.0 / nbPoints;
  7283. for (var i = 0; i <= nbPoints; i++) {
  7284. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7285. }
  7286. return new Curve3(hermite);
  7287. };
  7288. /**
  7289. * Returns a Curve3 object along a CatmullRom Spline curve :
  7290. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7291. * @param nbPoints (integer) the wanted number of points between each curve control points
  7292. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7293. */
  7294. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7295. var catmullRom = new Array();
  7296. var step = 1.0 / nbPoints;
  7297. var amount = 0.0;
  7298. if (closed) {
  7299. var pointsCount = points.length;
  7300. for (var i = 0; i < pointsCount; i++) {
  7301. amount = 0;
  7302. for (var c = 0; c < nbPoints; c++) {
  7303. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7304. amount += step;
  7305. }
  7306. }
  7307. catmullRom.push(catmullRom[0]);
  7308. }
  7309. else {
  7310. var totalPoints = new Array();
  7311. totalPoints.push(points[0].clone());
  7312. Array.prototype.push.apply(totalPoints, points);
  7313. totalPoints.push(points[points.length - 1].clone());
  7314. for (var i = 0; i < totalPoints.length - 3; i++) {
  7315. amount = 0;
  7316. for (var c = 0; c < nbPoints; c++) {
  7317. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7318. amount += step;
  7319. }
  7320. }
  7321. i--;
  7322. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7323. }
  7324. return new Curve3(catmullRom);
  7325. };
  7326. /**
  7327. * Returns the Curve3 stored array of successive Vector3
  7328. */
  7329. Curve3.prototype.getPoints = function () {
  7330. return this._points;
  7331. };
  7332. /**
  7333. * Returns the computed length (float) of the curve.
  7334. */
  7335. Curve3.prototype.length = function () {
  7336. return this._length;
  7337. };
  7338. /**
  7339. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7340. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7341. * curveA and curveB keep unchanged.
  7342. */
  7343. Curve3.prototype.continue = function (curve) {
  7344. var lastPoint = this._points[this._points.length - 1];
  7345. var continuedPoints = this._points.slice();
  7346. var curvePoints = curve.getPoints();
  7347. for (var i = 1; i < curvePoints.length; i++) {
  7348. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7349. }
  7350. var continuedCurve = new Curve3(continuedPoints);
  7351. return continuedCurve;
  7352. };
  7353. Curve3.prototype._computeLength = function (path) {
  7354. var l = 0;
  7355. for (var i = 1; i < path.length; i++) {
  7356. l += (path[i].subtract(path[i - 1])).length();
  7357. }
  7358. return l;
  7359. };
  7360. return Curve3;
  7361. }());
  7362. BABYLON.Curve3 = Curve3;
  7363. // Vertex formats
  7364. var PositionNormalVertex = /** @class */ (function () {
  7365. function PositionNormalVertex(position, normal) {
  7366. if (position === void 0) { position = Vector3.Zero(); }
  7367. if (normal === void 0) { normal = Vector3.Up(); }
  7368. this.position = position;
  7369. this.normal = normal;
  7370. }
  7371. PositionNormalVertex.prototype.clone = function () {
  7372. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7373. };
  7374. return PositionNormalVertex;
  7375. }());
  7376. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7377. var PositionNormalTextureVertex = /** @class */ (function () {
  7378. function PositionNormalTextureVertex(position, normal, uv) {
  7379. if (position === void 0) { position = Vector3.Zero(); }
  7380. if (normal === void 0) { normal = Vector3.Up(); }
  7381. if (uv === void 0) { uv = Vector2.Zero(); }
  7382. this.position = position;
  7383. this.normal = normal;
  7384. this.uv = uv;
  7385. }
  7386. PositionNormalTextureVertex.prototype.clone = function () {
  7387. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7388. };
  7389. return PositionNormalTextureVertex;
  7390. }());
  7391. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7392. // Temporary pre-allocated objects for engine internal use
  7393. // usage in any internal function :
  7394. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7395. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7396. var Tmp = /** @class */ (function () {
  7397. function Tmp() {
  7398. }
  7399. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7400. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7401. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7402. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7403. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7404. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7405. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7406. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7407. Matrix.Zero(), Matrix.Zero(),
  7408. Matrix.Zero(), Matrix.Zero(),
  7409. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7410. return Tmp;
  7411. }());
  7412. BABYLON.Tmp = Tmp;
  7413. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7414. var MathTmp = /** @class */ (function () {
  7415. function MathTmp() {
  7416. }
  7417. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7418. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7419. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7420. return MathTmp;
  7421. }());
  7422. })(BABYLON || (BABYLON = {}));
  7423. //# sourceMappingURL=babylon.math.js.map
  7424. var BABYLON;
  7425. (function (BABYLON) {
  7426. var Scalar = /** @class */ (function () {
  7427. function Scalar() {
  7428. }
  7429. /**
  7430. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7431. */
  7432. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7433. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7434. var num = a - b;
  7435. return -epsilon <= num && num <= epsilon;
  7436. };
  7437. /**
  7438. * Returns a string : the upper case translation of the number i to hexadecimal.
  7439. */
  7440. Scalar.ToHex = function (i) {
  7441. var str = i.toString(16);
  7442. if (i <= 15) {
  7443. return ("0" + str).toUpperCase();
  7444. }
  7445. return str.toUpperCase();
  7446. };
  7447. /**
  7448. * Returns -1 if value is negative and +1 is value is positive.
  7449. * Returns the value itself if it's equal to zero.
  7450. */
  7451. Scalar.Sign = function (value) {
  7452. value = +value; // convert to a number
  7453. if (value === 0 || isNaN(value))
  7454. return value;
  7455. return value > 0 ? 1 : -1;
  7456. };
  7457. /**
  7458. * Returns the value itself if it's between min and max.
  7459. * Returns min if the value is lower than min.
  7460. * Returns max if the value is greater than max.
  7461. */
  7462. Scalar.Clamp = function (value, min, max) {
  7463. if (min === void 0) { min = 0; }
  7464. if (max === void 0) { max = 1; }
  7465. return Math.min(max, Math.max(min, value));
  7466. };
  7467. /**
  7468. * Returns the log2 of value.
  7469. */
  7470. Scalar.Log2 = function (value) {
  7471. return Math.log(value) * Math.LOG2E;
  7472. };
  7473. /**
  7474. * Loops the value, so that it is never larger than length and never smaller than 0.
  7475. *
  7476. * This is similar to the modulo operator but it works with floating point numbers.
  7477. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7478. * With t = 5 and length = 2.5, the result would be 0.0.
  7479. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7480. */
  7481. Scalar.Repeat = function (value, length) {
  7482. return value - Math.floor(value / length) * length;
  7483. };
  7484. /**
  7485. * Normalize the value between 0.0 and 1.0 using min and max values
  7486. */
  7487. Scalar.Normalize = function (value, min, max) {
  7488. return (value - min) / (max - min);
  7489. };
  7490. /**
  7491. * Denormalize the value from 0.0 and 1.0 using min and max values
  7492. */
  7493. Scalar.Denormalize = function (normalized, min, max) {
  7494. return (normalized * (max - min) + min);
  7495. };
  7496. /**
  7497. * Calculates the shortest difference between two given angles given in degrees.
  7498. */
  7499. Scalar.DeltaAngle = function (current, target) {
  7500. var num = Scalar.Repeat(target - current, 360.0);
  7501. if (num > 180.0) {
  7502. num -= 360.0;
  7503. }
  7504. return num;
  7505. };
  7506. /**
  7507. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7508. *
  7509. * The returned value will move back and forth between 0 and length
  7510. */
  7511. Scalar.PingPong = function (tx, length) {
  7512. var t = Scalar.Repeat(tx, length * 2.0);
  7513. return length - Math.abs(t - length);
  7514. };
  7515. /**
  7516. * Interpolates between min and max with smoothing at the limits.
  7517. *
  7518. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7519. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7520. */
  7521. Scalar.SmoothStep = function (from, to, tx) {
  7522. var t = Scalar.Clamp(tx);
  7523. t = -2.0 * t * t * t + 3.0 * t * t;
  7524. return to * t + from * (1.0 - t);
  7525. };
  7526. /**
  7527. * Moves a value current towards target.
  7528. *
  7529. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7530. * Negative values of maxDelta pushes the value away from target.
  7531. */
  7532. Scalar.MoveTowards = function (current, target, maxDelta) {
  7533. var result = 0;
  7534. if (Math.abs(target - current) <= maxDelta) {
  7535. result = target;
  7536. }
  7537. else {
  7538. result = current + Scalar.Sign(target - current) * maxDelta;
  7539. }
  7540. return result;
  7541. };
  7542. /**
  7543. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7544. *
  7545. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7546. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7547. */
  7548. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7549. var num = Scalar.DeltaAngle(current, target);
  7550. var result = 0;
  7551. if (-maxDelta < num && num < maxDelta) {
  7552. result = target;
  7553. }
  7554. else {
  7555. target = current + num;
  7556. result = Scalar.MoveTowards(current, target, maxDelta);
  7557. }
  7558. return result;
  7559. };
  7560. /**
  7561. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7562. */
  7563. Scalar.Lerp = function (start, end, amount) {
  7564. return start + ((end - start) * amount);
  7565. };
  7566. /**
  7567. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7568. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7569. */
  7570. Scalar.LerpAngle = function (start, end, amount) {
  7571. var num = Scalar.Repeat(end - start, 360.0);
  7572. if (num > 180.0) {
  7573. num -= 360.0;
  7574. }
  7575. return start + num * Scalar.Clamp(amount);
  7576. };
  7577. /**
  7578. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7579. */
  7580. Scalar.InverseLerp = function (a, b, value) {
  7581. var result = 0;
  7582. if (a != b) {
  7583. result = Scalar.Clamp((value - a) / (b - a));
  7584. }
  7585. else {
  7586. result = 0.0;
  7587. }
  7588. return result;
  7589. };
  7590. /**
  7591. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7592. */
  7593. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7594. var squared = amount * amount;
  7595. var cubed = amount * squared;
  7596. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7597. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7598. var part3 = (cubed - (2.0 * squared)) + amount;
  7599. var part4 = cubed - squared;
  7600. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7601. };
  7602. /**
  7603. * Returns a random float number between and min and max values
  7604. */
  7605. Scalar.RandomRange = function (min, max) {
  7606. if (min === max)
  7607. return min;
  7608. return ((Math.random() * (max - min)) + min);
  7609. };
  7610. /**
  7611. * This function returns percentage of a number in a given range.
  7612. *
  7613. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7614. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7615. */
  7616. Scalar.RangeToPercent = function (number, min, max) {
  7617. return ((number - min) / (max - min));
  7618. };
  7619. /**
  7620. * This function returns number that corresponds to the percentage in a given range.
  7621. *
  7622. * PercentToRange(0.34,0,100) will return 34.
  7623. */
  7624. Scalar.PercentToRange = function (percent, min, max) {
  7625. return ((max - min) * percent + min);
  7626. };
  7627. /**
  7628. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7629. * @param angle The angle to normalize in radian.
  7630. * @return The converted angle.
  7631. */
  7632. Scalar.NormalizeRadians = function (angle) {
  7633. // More precise but slower version kept for reference.
  7634. // angle = angle % Tools.TwoPi;
  7635. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7636. //if (angle > Math.PI) {
  7637. // angle -= Tools.TwoPi;
  7638. //}
  7639. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7640. return angle;
  7641. };
  7642. /**
  7643. * Two pi constants convenient for computation.
  7644. */
  7645. Scalar.TwoPi = Math.PI * 2;
  7646. return Scalar;
  7647. }());
  7648. BABYLON.Scalar = Scalar;
  7649. })(BABYLON || (BABYLON = {}));
  7650. //# sourceMappingURL=babylon.math.scalar.js.map
  7651. //# sourceMappingURL=babylon.mixins.js.map
  7652. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7653. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7654. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7655. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7656. //# sourceMappingURL=babylon.webgl2.js.map
  7657. var BABYLON;
  7658. (function (BABYLON) {
  7659. var __decoratorInitialStore = {};
  7660. var __mergedStore = {};
  7661. var _copySource = function (creationFunction, source, instanciate) {
  7662. var destination = creationFunction();
  7663. // Tags
  7664. if (BABYLON.Tags) {
  7665. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7666. }
  7667. var classStore = getMergedStore(destination);
  7668. // Properties
  7669. for (var property in classStore) {
  7670. var propertyDescriptor = classStore[property];
  7671. var sourceProperty = source[property];
  7672. var propertyType = propertyDescriptor.type;
  7673. if (sourceProperty !== undefined && sourceProperty !== null) {
  7674. switch (propertyType) {
  7675. case 0: // Value
  7676. case 6: // Mesh reference
  7677. case 11: // Camera reference
  7678. destination[property] = sourceProperty;
  7679. break;
  7680. case 1: // Texture
  7681. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7682. break;
  7683. case 2: // Color3
  7684. case 3: // FresnelParameters
  7685. case 4: // Vector2
  7686. case 5: // Vector3
  7687. case 7: // Color Curves
  7688. case 10: // Quaternion
  7689. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7690. break;
  7691. }
  7692. }
  7693. }
  7694. return destination;
  7695. };
  7696. function getDirectStore(target) {
  7697. var classKey = target.getClassName();
  7698. if (!__decoratorInitialStore[classKey]) {
  7699. __decoratorInitialStore[classKey] = {};
  7700. }
  7701. return __decoratorInitialStore[classKey];
  7702. }
  7703. /**
  7704. * Return the list of properties flagged as serializable
  7705. * @param target: host object
  7706. */
  7707. function getMergedStore(target) {
  7708. var classKey = target.getClassName();
  7709. if (__mergedStore[classKey]) {
  7710. return __mergedStore[classKey];
  7711. }
  7712. __mergedStore[classKey] = {};
  7713. var store = __mergedStore[classKey];
  7714. var currentTarget = target;
  7715. var currentKey = classKey;
  7716. while (currentKey) {
  7717. var initialStore = __decoratorInitialStore[currentKey];
  7718. for (var property in initialStore) {
  7719. store[property] = initialStore[property];
  7720. }
  7721. var parent_1 = void 0;
  7722. var done = false;
  7723. do {
  7724. parent_1 = Object.getPrototypeOf(currentTarget);
  7725. if (!parent_1.getClassName) {
  7726. done = true;
  7727. break;
  7728. }
  7729. if (parent_1.getClassName() !== currentKey) {
  7730. break;
  7731. }
  7732. currentTarget = parent_1;
  7733. } while (parent_1);
  7734. if (done) {
  7735. break;
  7736. }
  7737. currentKey = parent_1.getClassName();
  7738. currentTarget = parent_1;
  7739. }
  7740. return store;
  7741. }
  7742. function generateSerializableMember(type, sourceName) {
  7743. return function (target, propertyKey) {
  7744. var classStore = getDirectStore(target);
  7745. if (!classStore[propertyKey]) {
  7746. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7747. }
  7748. };
  7749. }
  7750. function generateExpandMember(setCallback, targetKey) {
  7751. if (targetKey === void 0) { targetKey = null; }
  7752. return function (target, propertyKey) {
  7753. var key = targetKey || ("_" + propertyKey);
  7754. Object.defineProperty(target, propertyKey, {
  7755. get: function () {
  7756. return this[key];
  7757. },
  7758. set: function (value) {
  7759. if (this[key] === value) {
  7760. return;
  7761. }
  7762. this[key] = value;
  7763. target[setCallback].apply(this);
  7764. },
  7765. enumerable: true,
  7766. configurable: true
  7767. });
  7768. };
  7769. }
  7770. function expandToProperty(callback, targetKey) {
  7771. if (targetKey === void 0) { targetKey = null; }
  7772. return generateExpandMember(callback, targetKey);
  7773. }
  7774. BABYLON.expandToProperty = expandToProperty;
  7775. function serialize(sourceName) {
  7776. return generateSerializableMember(0, sourceName); // value member
  7777. }
  7778. BABYLON.serialize = serialize;
  7779. function serializeAsTexture(sourceName) {
  7780. return generateSerializableMember(1, sourceName); // texture member
  7781. }
  7782. BABYLON.serializeAsTexture = serializeAsTexture;
  7783. function serializeAsColor3(sourceName) {
  7784. return generateSerializableMember(2, sourceName); // color3 member
  7785. }
  7786. BABYLON.serializeAsColor3 = serializeAsColor3;
  7787. function serializeAsFresnelParameters(sourceName) {
  7788. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7789. }
  7790. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7791. function serializeAsVector2(sourceName) {
  7792. return generateSerializableMember(4, sourceName); // vector2 member
  7793. }
  7794. BABYLON.serializeAsVector2 = serializeAsVector2;
  7795. function serializeAsVector3(sourceName) {
  7796. return generateSerializableMember(5, sourceName); // vector3 member
  7797. }
  7798. BABYLON.serializeAsVector3 = serializeAsVector3;
  7799. function serializeAsMeshReference(sourceName) {
  7800. return generateSerializableMember(6, sourceName); // mesh reference member
  7801. }
  7802. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7803. function serializeAsColorCurves(sourceName) {
  7804. return generateSerializableMember(7, sourceName); // color curves
  7805. }
  7806. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7807. function serializeAsColor4(sourceName) {
  7808. return generateSerializableMember(8, sourceName); // color 4
  7809. }
  7810. BABYLON.serializeAsColor4 = serializeAsColor4;
  7811. function serializeAsImageProcessingConfiguration(sourceName) {
  7812. return generateSerializableMember(9, sourceName); // image processing
  7813. }
  7814. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7815. function serializeAsQuaternion(sourceName) {
  7816. return generateSerializableMember(10, sourceName); // quaternion member
  7817. }
  7818. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7819. /**
  7820. * Decorator used to define property that can be serialized as reference to a camera
  7821. * @param sourceName defines the name of the property to decorate
  7822. */
  7823. function serializeAsCameraReference(sourceName) {
  7824. return generateSerializableMember(11, sourceName); // camera reference member
  7825. }
  7826. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7827. var SerializationHelper = /** @class */ (function () {
  7828. function SerializationHelper() {
  7829. }
  7830. SerializationHelper.Serialize = function (entity, serializationObject) {
  7831. if (!serializationObject) {
  7832. serializationObject = {};
  7833. }
  7834. // Tags
  7835. if (BABYLON.Tags) {
  7836. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7837. }
  7838. var serializedProperties = getMergedStore(entity);
  7839. // Properties
  7840. for (var property in serializedProperties) {
  7841. var propertyDescriptor = serializedProperties[property];
  7842. var targetPropertyName = propertyDescriptor.sourceName || property;
  7843. var propertyType = propertyDescriptor.type;
  7844. var sourceProperty = entity[property];
  7845. if (sourceProperty !== undefined && sourceProperty !== null) {
  7846. switch (propertyType) {
  7847. case 0: // Value
  7848. serializationObject[targetPropertyName] = sourceProperty;
  7849. break;
  7850. case 1: // Texture
  7851. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7852. break;
  7853. case 2: // Color3
  7854. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7855. break;
  7856. case 3: // FresnelParameters
  7857. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7858. break;
  7859. case 4: // Vector2
  7860. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7861. break;
  7862. case 5: // Vector3
  7863. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7864. break;
  7865. case 6: // Mesh reference
  7866. serializationObject[targetPropertyName] = sourceProperty.id;
  7867. break;
  7868. case 7: // Color Curves
  7869. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7870. break;
  7871. case 8: // Color 4
  7872. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7873. break;
  7874. case 9: // Image Processing
  7875. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7876. break;
  7877. case 10: // Quaternion
  7878. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7879. break;
  7880. case 11: // Camera reference
  7881. serializationObject[targetPropertyName] = sourceProperty.id;
  7882. break;
  7883. }
  7884. }
  7885. }
  7886. return serializationObject;
  7887. };
  7888. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7889. if (rootUrl === void 0) { rootUrl = null; }
  7890. var destination = creationFunction();
  7891. if (!rootUrl) {
  7892. rootUrl = "";
  7893. }
  7894. // Tags
  7895. if (BABYLON.Tags) {
  7896. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7897. }
  7898. var classStore = getMergedStore(destination);
  7899. // Properties
  7900. for (var property in classStore) {
  7901. var propertyDescriptor = classStore[property];
  7902. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7903. var propertyType = propertyDescriptor.type;
  7904. if (sourceProperty !== undefined && sourceProperty !== null) {
  7905. var dest = destination;
  7906. switch (propertyType) {
  7907. case 0: // Value
  7908. dest[property] = sourceProperty;
  7909. break;
  7910. case 1: // Texture
  7911. if (scene) {
  7912. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7913. }
  7914. break;
  7915. case 2: // Color3
  7916. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7917. break;
  7918. case 3: // FresnelParameters
  7919. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7920. break;
  7921. case 4: // Vector2
  7922. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7923. break;
  7924. case 5: // Vector3
  7925. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7926. break;
  7927. case 6: // Mesh reference
  7928. if (scene) {
  7929. dest[property] = scene.getLastMeshByID(sourceProperty);
  7930. }
  7931. break;
  7932. case 7: // Color Curves
  7933. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7934. break;
  7935. case 8: // Color 4
  7936. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7937. break;
  7938. case 9: // Image Processing
  7939. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7940. break;
  7941. case 10: // Quaternion
  7942. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7943. break;
  7944. case 11: // Camera reference
  7945. if (scene) {
  7946. dest[property] = scene.getCameraByID(sourceProperty);
  7947. }
  7948. break;
  7949. }
  7950. }
  7951. }
  7952. return destination;
  7953. };
  7954. SerializationHelper.Clone = function (creationFunction, source) {
  7955. return _copySource(creationFunction, source, false);
  7956. };
  7957. SerializationHelper.Instanciate = function (creationFunction, source) {
  7958. return _copySource(creationFunction, source, true);
  7959. };
  7960. return SerializationHelper;
  7961. }());
  7962. BABYLON.SerializationHelper = SerializationHelper;
  7963. })(BABYLON || (BABYLON = {}));
  7964. //# sourceMappingURL=babylon.decorators.js.map
  7965. var BABYLON;
  7966. (function (BABYLON) {
  7967. /**
  7968. * Wrapper class for promise with external resolve and reject.
  7969. */
  7970. var Deferred = /** @class */ (function () {
  7971. /**
  7972. * Constructor for this deferred object.
  7973. */
  7974. function Deferred() {
  7975. var _this = this;
  7976. this.promise = new Promise(function (resolve, reject) {
  7977. _this._resolve = resolve;
  7978. _this._reject = reject;
  7979. });
  7980. }
  7981. Object.defineProperty(Deferred.prototype, "resolve", {
  7982. /**
  7983. * The resolve method of the promise associated with this deferred object.
  7984. */
  7985. get: function () {
  7986. return this._resolve;
  7987. },
  7988. enumerable: true,
  7989. configurable: true
  7990. });
  7991. Object.defineProperty(Deferred.prototype, "reject", {
  7992. /**
  7993. * The reject method of the promise associated with this deferred object.
  7994. */
  7995. get: function () {
  7996. return this._reject;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. return Deferred;
  8002. }());
  8003. BABYLON.Deferred = Deferred;
  8004. })(BABYLON || (BABYLON = {}));
  8005. //# sourceMappingURL=babylon.deferred.js.map
  8006. var BABYLON;
  8007. (function (BABYLON) {
  8008. /**
  8009. * A class serves as a medium between the observable and its observers
  8010. */
  8011. var EventState = /** @class */ (function () {
  8012. /**
  8013. * Create a new EventState
  8014. * @param mask defines the mask associated with this state
  8015. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8016. * @param target defines the original target of the state
  8017. * @param currentTarget defines the current target of the state
  8018. */
  8019. function EventState(mask, skipNextObservers, target, currentTarget) {
  8020. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8021. this.initalize(mask, skipNextObservers, target, currentTarget);
  8022. }
  8023. /**
  8024. * Initialize the current event state
  8025. * @param mask defines the mask associated with this state
  8026. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8027. * @param target defines the original target of the state
  8028. * @param currentTarget defines the current target of the state
  8029. * @returns the current event state
  8030. */
  8031. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8032. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8033. this.mask = mask;
  8034. this.skipNextObservers = skipNextObservers;
  8035. this.target = target;
  8036. this.currentTarget = currentTarget;
  8037. return this;
  8038. };
  8039. return EventState;
  8040. }());
  8041. BABYLON.EventState = EventState;
  8042. /**
  8043. * Represent an Observer registered to a given Observable object.
  8044. */
  8045. var Observer = /** @class */ (function () {
  8046. /**
  8047. * Creates a new observer
  8048. * @param callback defines the callback to call when the observer is notified
  8049. * @param mask defines the mask of the observer (used to filter notifications)
  8050. * @param scope defines the current scope used to restore the JS context
  8051. */
  8052. function Observer(
  8053. /**
  8054. * Defines the callback to call when the observer is notified
  8055. */
  8056. callback,
  8057. /**
  8058. * Defines the mask of the observer (used to filter notifications)
  8059. */
  8060. mask,
  8061. /**
  8062. * Defines the current scope used to restore the JS context
  8063. */
  8064. scope) {
  8065. if (scope === void 0) { scope = null; }
  8066. this.callback = callback;
  8067. this.mask = mask;
  8068. this.scope = scope;
  8069. /** @hidden */
  8070. this._willBeUnregistered = false;
  8071. /**
  8072. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8073. */
  8074. this.unregisterOnNextCall = false;
  8075. }
  8076. return Observer;
  8077. }());
  8078. BABYLON.Observer = Observer;
  8079. /**
  8080. * Represent a list of observers registered to multiple Observables object.
  8081. */
  8082. var MultiObserver = /** @class */ (function () {
  8083. function MultiObserver() {
  8084. }
  8085. /**
  8086. * Release associated resources
  8087. */
  8088. MultiObserver.prototype.dispose = function () {
  8089. if (this._observers && this._observables) {
  8090. for (var index = 0; index < this._observers.length; index++) {
  8091. this._observables[index].remove(this._observers[index]);
  8092. }
  8093. }
  8094. this._observers = null;
  8095. this._observables = null;
  8096. };
  8097. /**
  8098. * Raise a callback when one of the observable will notify
  8099. * @param observables defines a list of observables to watch
  8100. * @param callback defines the callback to call on notification
  8101. * @param mask defines the mask used to filter notifications
  8102. * @param scope defines the current scope used to restore the JS context
  8103. * @returns the new MultiObserver
  8104. */
  8105. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8106. if (mask === void 0) { mask = -1; }
  8107. if (scope === void 0) { scope = null; }
  8108. var result = new MultiObserver();
  8109. result._observers = new Array();
  8110. result._observables = observables;
  8111. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8112. var observable = observables_1[_i];
  8113. var observer = observable.add(callback, mask, false, scope);
  8114. if (observer) {
  8115. result._observers.push(observer);
  8116. }
  8117. }
  8118. return result;
  8119. };
  8120. return MultiObserver;
  8121. }());
  8122. BABYLON.MultiObserver = MultiObserver;
  8123. /**
  8124. * The Observable class is a simple implementation of the Observable pattern.
  8125. *
  8126. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  8127. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8128. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  8129. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  8130. */
  8131. var Observable = /** @class */ (function () {
  8132. /**
  8133. * Creates a new observable
  8134. * @param onObserverAdded defines a callback to call when a new observer is added
  8135. */
  8136. function Observable(onObserverAdded) {
  8137. this._observers = new Array();
  8138. this._eventState = new EventState(0);
  8139. if (onObserverAdded) {
  8140. this._onObserverAdded = onObserverAdded;
  8141. }
  8142. }
  8143. /**
  8144. * Create a new Observer with the specified callback
  8145. * @param callback the callback that will be executed for that Observer
  8146. * @param mask the mask used to filter observers
  8147. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  8148. * @param scope optional scope for the callback to be called from
  8149. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8150. * @returns the new observer created for the callback
  8151. */
  8152. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8153. if (mask === void 0) { mask = -1; }
  8154. if (insertFirst === void 0) { insertFirst = false; }
  8155. if (scope === void 0) { scope = null; }
  8156. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8157. if (!callback) {
  8158. return null;
  8159. }
  8160. var observer = new Observer(callback, mask, scope);
  8161. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8162. if (insertFirst) {
  8163. this._observers.unshift(observer);
  8164. }
  8165. else {
  8166. this._observers.push(observer);
  8167. }
  8168. if (this._onObserverAdded) {
  8169. this._onObserverAdded(observer);
  8170. }
  8171. return observer;
  8172. };
  8173. /**
  8174. * Create a new Observer with the specified callback and unregisters after the next notification
  8175. * @param callback the callback that will be executed for that Observer
  8176. * @returns the new observer created for the callback
  8177. */
  8178. Observable.prototype.addOnce = function (callback) {
  8179. return this.add(callback, undefined, undefined, undefined, true);
  8180. };
  8181. /**
  8182. * Remove an Observer from the Observable object
  8183. * @param observer the instance of the Observer to remove
  8184. * @returns false if it doesn't belong to this Observable
  8185. */
  8186. Observable.prototype.remove = function (observer) {
  8187. if (!observer) {
  8188. return false;
  8189. }
  8190. var index = this._observers.indexOf(observer);
  8191. if (index !== -1) {
  8192. this._deferUnregister(observer);
  8193. return true;
  8194. }
  8195. return false;
  8196. };
  8197. /**
  8198. * Remove a callback from the Observable object
  8199. * @param callback the callback to remove
  8200. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8201. * @returns false if it doesn't belong to this Observable
  8202. */
  8203. Observable.prototype.removeCallback = function (callback, scope) {
  8204. for (var index = 0; index < this._observers.length; index++) {
  8205. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8206. this._deferUnregister(this._observers[index]);
  8207. return true;
  8208. }
  8209. }
  8210. return false;
  8211. };
  8212. Observable.prototype._deferUnregister = function (observer) {
  8213. var _this = this;
  8214. observer.unregisterOnNextCall = false;
  8215. observer._willBeUnregistered = true;
  8216. BABYLON.Tools.SetImmediate(function () {
  8217. _this._remove(observer);
  8218. });
  8219. };
  8220. // This should only be called when not iterating over _observers to avoid callback skipping.
  8221. // Removes an observer from the _observer Array.
  8222. Observable.prototype._remove = function (observer) {
  8223. if (!observer) {
  8224. return false;
  8225. }
  8226. var index = this._observers.indexOf(observer);
  8227. if (index !== -1) {
  8228. this._observers.splice(index, 1);
  8229. return true;
  8230. }
  8231. return false;
  8232. };
  8233. /**
  8234. * Notify all Observers by calling their respective callback with the given data
  8235. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8236. * @param eventData defines the data to send to all observers
  8237. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8238. * @param target defines the original target of the state
  8239. * @param currentTarget defines the current target of the state
  8240. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8241. */
  8242. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8243. if (mask === void 0) { mask = -1; }
  8244. if (!this._observers.length) {
  8245. return true;
  8246. }
  8247. var state = this._eventState;
  8248. state.mask = mask;
  8249. state.target = target;
  8250. state.currentTarget = currentTarget;
  8251. state.skipNextObservers = false;
  8252. state.lastReturnValue = eventData;
  8253. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8254. var obs = _a[_i];
  8255. if (obs._willBeUnregistered) {
  8256. continue;
  8257. }
  8258. if (obs.mask & mask) {
  8259. if (obs.scope) {
  8260. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8261. }
  8262. else {
  8263. state.lastReturnValue = obs.callback(eventData, state);
  8264. }
  8265. if (obs.unregisterOnNextCall) {
  8266. this._deferUnregister(obs);
  8267. }
  8268. }
  8269. if (state.skipNextObservers) {
  8270. return false;
  8271. }
  8272. }
  8273. return true;
  8274. };
  8275. /**
  8276. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8277. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8278. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8279. * and it is crucial that all callbacks will be executed.
  8280. * The order of the callbacks is kept, callbacks are not executed parallel.
  8281. *
  8282. * @param eventData The data to be sent to each callback
  8283. * @param mask is used to filter observers defaults to -1
  8284. * @param target defines the callback target (see EventState)
  8285. * @param currentTarget defines he current object in the bubbling phase
  8286. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8287. */
  8288. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8289. var _this = this;
  8290. if (mask === void 0) { mask = -1; }
  8291. // create an empty promise
  8292. var p = Promise.resolve(eventData);
  8293. // no observers? return this promise.
  8294. if (!this._observers.length) {
  8295. return p;
  8296. }
  8297. var state = this._eventState;
  8298. state.mask = mask;
  8299. state.target = target;
  8300. state.currentTarget = currentTarget;
  8301. state.skipNextObservers = false;
  8302. // execute one callback after another (not using Promise.all, the order is important)
  8303. this._observers.forEach(function (obs) {
  8304. if (state.skipNextObservers) {
  8305. return;
  8306. }
  8307. if (obs._willBeUnregistered) {
  8308. return;
  8309. }
  8310. if (obs.mask & mask) {
  8311. if (obs.scope) {
  8312. p = p.then(function (lastReturnedValue) {
  8313. state.lastReturnValue = lastReturnedValue;
  8314. return obs.callback.apply(obs.scope, [eventData, state]);
  8315. });
  8316. }
  8317. else {
  8318. p = p.then(function (lastReturnedValue) {
  8319. state.lastReturnValue = lastReturnedValue;
  8320. return obs.callback(eventData, state);
  8321. });
  8322. }
  8323. if (obs.unregisterOnNextCall) {
  8324. _this._deferUnregister(obs);
  8325. }
  8326. }
  8327. });
  8328. // return the eventData
  8329. return p.then(function () { return eventData; });
  8330. };
  8331. /**
  8332. * Notify a specific observer
  8333. * @param observer defines the observer to notify
  8334. * @param eventData defines the data to be sent to each callback
  8335. * @param mask is used to filter observers defaults to -1
  8336. */
  8337. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8338. if (mask === void 0) { mask = -1; }
  8339. var state = this._eventState;
  8340. state.mask = mask;
  8341. state.skipNextObservers = false;
  8342. observer.callback(eventData, state);
  8343. };
  8344. /**
  8345. * Gets a boolean indicating if the observable has at least one observer
  8346. * @returns true is the Observable has at least one Observer registered
  8347. */
  8348. Observable.prototype.hasObservers = function () {
  8349. return this._observers.length > 0;
  8350. };
  8351. /**
  8352. * Clear the list of observers
  8353. */
  8354. Observable.prototype.clear = function () {
  8355. this._observers = new Array();
  8356. this._onObserverAdded = null;
  8357. };
  8358. /**
  8359. * Clone the current observable
  8360. * @returns a new observable
  8361. */
  8362. Observable.prototype.clone = function () {
  8363. var result = new Observable();
  8364. result._observers = this._observers.slice(0);
  8365. return result;
  8366. };
  8367. /**
  8368. * Does this observable handles observer registered with a given mask
  8369. * @param mask defines the mask to be tested
  8370. * @return whether or not one observer registered with the given mask is handeled
  8371. **/
  8372. Observable.prototype.hasSpecificMask = function (mask) {
  8373. if (mask === void 0) { mask = -1; }
  8374. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8375. var obs = _a[_i];
  8376. if (obs.mask & mask || obs.mask === mask) {
  8377. return true;
  8378. }
  8379. }
  8380. return false;
  8381. };
  8382. return Observable;
  8383. }());
  8384. BABYLON.Observable = Observable;
  8385. })(BABYLON || (BABYLON = {}));
  8386. //# sourceMappingURL=babylon.observable.js.map
  8387. var BABYLON;
  8388. (function (BABYLON) {
  8389. var SmartArray = /** @class */ (function () {
  8390. function SmartArray(capacity) {
  8391. this.length = 0;
  8392. this.data = new Array(capacity);
  8393. this._id = SmartArray._GlobalId++;
  8394. }
  8395. SmartArray.prototype.push = function (value) {
  8396. this.data[this.length++] = value;
  8397. if (this.length > this.data.length) {
  8398. this.data.length *= 2;
  8399. }
  8400. };
  8401. SmartArray.prototype.forEach = function (func) {
  8402. for (var index = 0; index < this.length; index++) {
  8403. func(this.data[index]);
  8404. }
  8405. };
  8406. SmartArray.prototype.sort = function (compareFn) {
  8407. this.data.sort(compareFn);
  8408. };
  8409. SmartArray.prototype.reset = function () {
  8410. this.length = 0;
  8411. };
  8412. SmartArray.prototype.dispose = function () {
  8413. this.reset();
  8414. if (this.data) {
  8415. this.data.length = 0;
  8416. this.data = [];
  8417. }
  8418. };
  8419. SmartArray.prototype.concat = function (array) {
  8420. if (array.length === 0) {
  8421. return;
  8422. }
  8423. if (this.length + array.length > this.data.length) {
  8424. this.data.length = (this.length + array.length) * 2;
  8425. }
  8426. for (var index = 0; index < array.length; index++) {
  8427. this.data[this.length++] = (array.data || array)[index];
  8428. }
  8429. };
  8430. SmartArray.prototype.indexOf = function (value) {
  8431. var position = this.data.indexOf(value);
  8432. if (position >= this.length) {
  8433. return -1;
  8434. }
  8435. return position;
  8436. };
  8437. SmartArray.prototype.contains = function (value) {
  8438. return this.data.indexOf(value) !== -1;
  8439. };
  8440. // Statics
  8441. SmartArray._GlobalId = 0;
  8442. return SmartArray;
  8443. }());
  8444. BABYLON.SmartArray = SmartArray;
  8445. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8446. __extends(SmartArrayNoDuplicate, _super);
  8447. function SmartArrayNoDuplicate() {
  8448. var _this = _super !== null && _super.apply(this, arguments) || this;
  8449. _this._duplicateId = 0;
  8450. return _this;
  8451. }
  8452. SmartArrayNoDuplicate.prototype.push = function (value) {
  8453. _super.prototype.push.call(this, value);
  8454. if (!value.__smartArrayFlags) {
  8455. value.__smartArrayFlags = {};
  8456. }
  8457. value.__smartArrayFlags[this._id] = this._duplicateId;
  8458. };
  8459. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8460. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8461. return false;
  8462. }
  8463. this.push(value);
  8464. return true;
  8465. };
  8466. SmartArrayNoDuplicate.prototype.reset = function () {
  8467. _super.prototype.reset.call(this);
  8468. this._duplicateId++;
  8469. };
  8470. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8471. if (array.length === 0) {
  8472. return;
  8473. }
  8474. if (this.length + array.length > this.data.length) {
  8475. this.data.length = (this.length + array.length) * 2;
  8476. }
  8477. for (var index = 0; index < array.length; index++) {
  8478. var item = (array.data || array)[index];
  8479. this.pushNoDuplicate(item);
  8480. }
  8481. };
  8482. return SmartArrayNoDuplicate;
  8483. }(SmartArray));
  8484. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8485. })(BABYLON || (BABYLON = {}));
  8486. //# sourceMappingURL=babylon.smartArray.js.map
  8487. var BABYLON;
  8488. (function (BABYLON) {
  8489. /** Class used to store color gradient */
  8490. var ColorGradient = /** @class */ (function () {
  8491. function ColorGradient() {
  8492. }
  8493. /**
  8494. * Will get a color picked randomly between color1 and color2.
  8495. * If color2 is undefined then color1 will be used
  8496. * @param result defines the target Color4 to store the result in
  8497. */
  8498. ColorGradient.prototype.getColorToRef = function (result) {
  8499. if (!this.color2) {
  8500. result.copyFrom(this.color1);
  8501. return;
  8502. }
  8503. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8504. };
  8505. return ColorGradient;
  8506. }());
  8507. BABYLON.ColorGradient = ColorGradient;
  8508. /** Class used to store factor gradient */
  8509. var FactorGradient = /** @class */ (function () {
  8510. function FactorGradient() {
  8511. }
  8512. /**
  8513. * Will get a number picked randomly between factor1 and factor2.
  8514. * If factor2 is undefined then factor1 will be used
  8515. * @returns the picked number
  8516. */
  8517. FactorGradient.prototype.getFactor = function () {
  8518. if (this.factor2 === undefined) {
  8519. return this.factor1;
  8520. }
  8521. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8522. };
  8523. return FactorGradient;
  8524. }());
  8525. BABYLON.FactorGradient = FactorGradient;
  8526. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8527. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8528. var LoadFileError = /** @class */ (function (_super) {
  8529. __extends(LoadFileError, _super);
  8530. function LoadFileError(message, request) {
  8531. var _this = _super.call(this, message) || this;
  8532. _this.request = request;
  8533. _this.name = "LoadFileError";
  8534. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8535. return _this;
  8536. }
  8537. // Polyfill for Object.setPrototypeOf if necessary.
  8538. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8539. return LoadFileError;
  8540. }(Error));
  8541. BABYLON.LoadFileError = LoadFileError;
  8542. var RetryStrategy = /** @class */ (function () {
  8543. function RetryStrategy() {
  8544. }
  8545. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8546. if (maxRetries === void 0) { maxRetries = 3; }
  8547. if (baseInterval === void 0) { baseInterval = 500; }
  8548. return function (url, request, retryIndex) {
  8549. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8550. return -1;
  8551. }
  8552. return Math.pow(2, retryIndex) * baseInterval;
  8553. };
  8554. };
  8555. return RetryStrategy;
  8556. }());
  8557. BABYLON.RetryStrategy = RetryStrategy;
  8558. // Screenshots
  8559. var screenshotCanvas;
  8560. var cloneValue = function (source, destinationObject) {
  8561. if (!source)
  8562. return null;
  8563. if (source instanceof BABYLON.Mesh) {
  8564. return null;
  8565. }
  8566. if (source instanceof BABYLON.SubMesh) {
  8567. return source.clone(destinationObject);
  8568. }
  8569. else if (source.clone) {
  8570. return source.clone();
  8571. }
  8572. return null;
  8573. };
  8574. var Tools = /** @class */ (function () {
  8575. function Tools() {
  8576. }
  8577. /**
  8578. * Interpolates between a and b via alpha
  8579. * @param a The lower value (returned when alpha = 0)
  8580. * @param b The upper value (returned when alpha = 1)
  8581. * @param alpha The interpolation-factor
  8582. * @return The mixed value
  8583. */
  8584. Tools.Mix = function (a, b, alpha) {
  8585. return a * (1 - alpha) + b * alpha;
  8586. };
  8587. Tools.Instantiate = function (className) {
  8588. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8589. return Tools.RegisteredExternalClasses[className];
  8590. }
  8591. var arr = className.split(".");
  8592. var fn = (window || this);
  8593. for (var i = 0, len = arr.length; i < len; i++) {
  8594. fn = fn[arr[i]];
  8595. }
  8596. if (typeof fn !== "function") {
  8597. return null;
  8598. }
  8599. return fn;
  8600. };
  8601. /**
  8602. * Provides a slice function that will work even on IE
  8603. * @param data defines the array to slice
  8604. * @param start defines the start of the data (optional)
  8605. * @param end defines the end of the data (optional)
  8606. * @returns the new sliced array
  8607. */
  8608. Tools.Slice = function (data, start, end) {
  8609. if (data.slice) {
  8610. return data.slice(start, end);
  8611. }
  8612. return Array.prototype.slice.call(data, start, end);
  8613. };
  8614. Tools.SetImmediate = function (action) {
  8615. if (window.setImmediate) {
  8616. window.setImmediate(action);
  8617. }
  8618. else {
  8619. setTimeout(action, 1);
  8620. }
  8621. };
  8622. Tools.IsExponentOfTwo = function (value) {
  8623. var count = 1;
  8624. do {
  8625. count *= 2;
  8626. } while (count < value);
  8627. return count === value;
  8628. };
  8629. /**
  8630. * Returns the nearest 32-bit single precision float representation of a Number
  8631. * @param value A Number. If the parameter is of a different type, it will get converted
  8632. * to a number or to NaN if it cannot be converted
  8633. * @returns number
  8634. */
  8635. Tools.FloatRound = function (value) {
  8636. if (Math.fround) {
  8637. return Math.fround(value);
  8638. }
  8639. return (Tools._tmpFloatArray[0] = value);
  8640. };
  8641. /**
  8642. * Find the next highest power of two.
  8643. * @param x Number to start search from.
  8644. * @return Next highest power of two.
  8645. */
  8646. Tools.CeilingPOT = function (x) {
  8647. x--;
  8648. x |= x >> 1;
  8649. x |= x >> 2;
  8650. x |= x >> 4;
  8651. x |= x >> 8;
  8652. x |= x >> 16;
  8653. x++;
  8654. return x;
  8655. };
  8656. /**
  8657. * Find the next lowest power of two.
  8658. * @param x Number to start search from.
  8659. * @return Next lowest power of two.
  8660. */
  8661. Tools.FloorPOT = function (x) {
  8662. x = x | (x >> 1);
  8663. x = x | (x >> 2);
  8664. x = x | (x >> 4);
  8665. x = x | (x >> 8);
  8666. x = x | (x >> 16);
  8667. return x - (x >> 1);
  8668. };
  8669. /**
  8670. * Find the nearest power of two.
  8671. * @param x Number to start search from.
  8672. * @return Next nearest power of two.
  8673. */
  8674. Tools.NearestPOT = function (x) {
  8675. var c = Tools.CeilingPOT(x);
  8676. var f = Tools.FloorPOT(x);
  8677. return (c - x) > (x - f) ? f : c;
  8678. };
  8679. Tools.GetExponentOfTwo = function (value, max, mode) {
  8680. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8681. var pot;
  8682. switch (mode) {
  8683. case BABYLON.Engine.SCALEMODE_FLOOR:
  8684. pot = Tools.FloorPOT(value);
  8685. break;
  8686. case BABYLON.Engine.SCALEMODE_NEAREST:
  8687. pot = Tools.NearestPOT(value);
  8688. break;
  8689. case BABYLON.Engine.SCALEMODE_CEILING:
  8690. default:
  8691. pot = Tools.CeilingPOT(value);
  8692. break;
  8693. }
  8694. return Math.min(pot, max);
  8695. };
  8696. Tools.GetFilename = function (path) {
  8697. var index = path.lastIndexOf("/");
  8698. if (index < 0)
  8699. return path;
  8700. return path.substring(index + 1);
  8701. };
  8702. /**
  8703. * Extracts the "folder" part of a path (everything before the filename).
  8704. * @param uri The URI to extract the info from
  8705. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8706. * @returns The "folder" part of the path
  8707. */
  8708. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8709. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8710. var index = uri.lastIndexOf("/");
  8711. if (index < 0) {
  8712. if (returnUnchangedIfNoSlash) {
  8713. return uri;
  8714. }
  8715. return "";
  8716. }
  8717. return uri.substring(0, index + 1);
  8718. };
  8719. Tools.GetDOMTextContent = function (element) {
  8720. var result = "";
  8721. var child = element.firstChild;
  8722. while (child) {
  8723. if (child.nodeType === 3) {
  8724. result += child.textContent;
  8725. }
  8726. child = child.nextSibling;
  8727. }
  8728. return result;
  8729. };
  8730. Tools.ToDegrees = function (angle) {
  8731. return angle * 180 / Math.PI;
  8732. };
  8733. Tools.ToRadians = function (angle) {
  8734. return angle * Math.PI / 180;
  8735. };
  8736. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8737. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8738. var output = "";
  8739. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8740. var i = 0;
  8741. var bytes = new Uint8Array(buffer);
  8742. while (i < bytes.length) {
  8743. chr1 = bytes[i++];
  8744. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8745. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8746. enc1 = chr1 >> 2;
  8747. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8748. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8749. enc4 = chr3 & 63;
  8750. if (isNaN(chr2)) {
  8751. enc3 = enc4 = 64;
  8752. }
  8753. else if (isNaN(chr3)) {
  8754. enc4 = 64;
  8755. }
  8756. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8757. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8758. }
  8759. return "data:image/png;base64," + output;
  8760. };
  8761. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8762. if (bias === void 0) { bias = null; }
  8763. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8764. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8765. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8766. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8767. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8768. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8769. }
  8770. if (bias) {
  8771. minimum.x -= minimum.x * bias.x + bias.y;
  8772. minimum.y -= minimum.y * bias.x + bias.y;
  8773. minimum.z -= minimum.z * bias.x + bias.y;
  8774. maximum.x += maximum.x * bias.x + bias.y;
  8775. maximum.y += maximum.y * bias.x + bias.y;
  8776. maximum.z += maximum.z * bias.x + bias.y;
  8777. }
  8778. return {
  8779. minimum: minimum,
  8780. maximum: maximum
  8781. };
  8782. };
  8783. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8784. if (bias === void 0) { bias = null; }
  8785. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8786. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8787. if (!stride) {
  8788. stride = 3;
  8789. }
  8790. for (var index = start; index < start + count; index++) {
  8791. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8792. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8793. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8794. }
  8795. if (bias) {
  8796. minimum.x -= minimum.x * bias.x + bias.y;
  8797. minimum.y -= minimum.y * bias.x + bias.y;
  8798. minimum.z -= minimum.z * bias.x + bias.y;
  8799. maximum.x += maximum.x * bias.x + bias.y;
  8800. maximum.y += maximum.y * bias.x + bias.y;
  8801. maximum.z += maximum.z * bias.x + bias.y;
  8802. }
  8803. return {
  8804. minimum: minimum,
  8805. maximum: maximum
  8806. };
  8807. };
  8808. Tools.Vector2ArrayFeeder = function (array) {
  8809. return function (index) {
  8810. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8811. var length = isFloatArray ? array.length / 2 : array.length;
  8812. if (index >= length) {
  8813. return null;
  8814. }
  8815. if (isFloatArray) {
  8816. var fa = array;
  8817. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8818. }
  8819. var a = array;
  8820. return a[index];
  8821. };
  8822. };
  8823. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8824. if (bias === void 0) { bias = null; }
  8825. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8826. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8827. var i = 0;
  8828. var cur = feeder(i++);
  8829. while (cur) {
  8830. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8831. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8832. cur = feeder(i++);
  8833. }
  8834. if (bias) {
  8835. minimum.x -= minimum.x * bias.x + bias.y;
  8836. minimum.y -= minimum.y * bias.x + bias.y;
  8837. maximum.x += maximum.x * bias.x + bias.y;
  8838. maximum.y += maximum.y * bias.x + bias.y;
  8839. }
  8840. return {
  8841. minimum: minimum,
  8842. maximum: maximum
  8843. };
  8844. };
  8845. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8846. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8847. return null;
  8848. return Array.isArray(obj) ? obj : [obj];
  8849. };
  8850. // Misc.
  8851. Tools.GetPointerPrefix = function () {
  8852. var eventPrefix = "pointer";
  8853. // Check if pointer events are supported
  8854. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8855. eventPrefix = "mouse";
  8856. }
  8857. return eventPrefix;
  8858. };
  8859. /**
  8860. * @param func - the function to be called
  8861. * @param requester - the object that will request the next frame. Falls back to window.
  8862. */
  8863. Tools.QueueNewFrame = function (func, requester) {
  8864. if (!Tools.IsWindowObjectExist()) {
  8865. return setTimeout(func, 16);
  8866. }
  8867. if (!requester) {
  8868. requester = window;
  8869. }
  8870. if (requester.requestAnimationFrame) {
  8871. return requester.requestAnimationFrame(func);
  8872. }
  8873. else if (requester.msRequestAnimationFrame) {
  8874. return requester.msRequestAnimationFrame(func);
  8875. }
  8876. else if (requester.webkitRequestAnimationFrame) {
  8877. return requester.webkitRequestAnimationFrame(func);
  8878. }
  8879. else if (requester.mozRequestAnimationFrame) {
  8880. return requester.mozRequestAnimationFrame(func);
  8881. }
  8882. else if (requester.oRequestAnimationFrame) {
  8883. return requester.oRequestAnimationFrame(func);
  8884. }
  8885. else {
  8886. return window.setTimeout(func, 16);
  8887. }
  8888. };
  8889. Tools.RequestFullscreen = function (element) {
  8890. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8891. if (!requestFunction)
  8892. return;
  8893. requestFunction.call(element);
  8894. };
  8895. Tools.ExitFullscreen = function () {
  8896. if (document.exitFullscreen) {
  8897. document.exitFullscreen();
  8898. }
  8899. else if (document.mozCancelFullScreen) {
  8900. document.mozCancelFullScreen();
  8901. }
  8902. else if (document.webkitCancelFullScreen) {
  8903. document.webkitCancelFullScreen();
  8904. }
  8905. else if (document.msCancelFullScreen) {
  8906. document.msCancelFullScreen();
  8907. }
  8908. };
  8909. Tools.SetCorsBehavior = function (url, element) {
  8910. if (url && url.indexOf("data:") === 0) {
  8911. return;
  8912. }
  8913. if (Tools.CorsBehavior) {
  8914. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8915. element.crossOrigin = Tools.CorsBehavior;
  8916. }
  8917. else {
  8918. var result = Tools.CorsBehavior(url);
  8919. if (result) {
  8920. element.crossOrigin = result;
  8921. }
  8922. }
  8923. }
  8924. };
  8925. // External files
  8926. Tools.CleanUrl = function (url) {
  8927. url = url.replace(/#/mg, "%23");
  8928. return url;
  8929. };
  8930. /**
  8931. * Loads an image as an HTMLImageElement.
  8932. * @param input url string, ArrayBuffer, or Blob to load
  8933. * @param onLoad callback called when the image successfully loads
  8934. * @param onError callback called when the image fails to load
  8935. * @param database database for caching
  8936. * @returns the HTMLImageElement of the loaded image
  8937. */
  8938. Tools.LoadImage = function (input, onLoad, onError, database) {
  8939. var url;
  8940. var usingObjectURL = false;
  8941. if (input instanceof ArrayBuffer) {
  8942. url = URL.createObjectURL(new Blob([input]));
  8943. usingObjectURL = true;
  8944. }
  8945. else if (input instanceof Blob) {
  8946. url = URL.createObjectURL(input);
  8947. usingObjectURL = true;
  8948. }
  8949. else {
  8950. url = Tools.CleanUrl(input);
  8951. url = Tools.PreprocessUrl(input);
  8952. }
  8953. var img = new Image();
  8954. Tools.SetCorsBehavior(url, img);
  8955. var loadHandler = function () {
  8956. if (usingObjectURL && img.src) {
  8957. URL.revokeObjectURL(img.src);
  8958. }
  8959. img.removeEventListener("load", loadHandler);
  8960. img.removeEventListener("error", errorHandler);
  8961. onLoad(img);
  8962. };
  8963. var errorHandler = function (err) {
  8964. if (usingObjectURL && img.src) {
  8965. URL.revokeObjectURL(img.src);
  8966. }
  8967. img.removeEventListener("load", loadHandler);
  8968. img.removeEventListener("error", errorHandler);
  8969. Tools.Error("Error while trying to load image: " + input);
  8970. if (onError) {
  8971. onError("Error while trying to load image: " + input, err);
  8972. }
  8973. };
  8974. img.addEventListener("load", loadHandler);
  8975. img.addEventListener("error", errorHandler);
  8976. var noIndexedDB = function () {
  8977. img.src = url;
  8978. };
  8979. var loadFromIndexedDB = function () {
  8980. if (database) {
  8981. database.loadImageFromDB(url, img);
  8982. }
  8983. };
  8984. //ANY database to do!
  8985. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8986. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8987. }
  8988. else {
  8989. if (url.indexOf("file:") !== -1) {
  8990. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8991. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8992. try {
  8993. var blobURL;
  8994. try {
  8995. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8996. }
  8997. catch (ex) {
  8998. // Chrome doesn't support oneTimeOnly parameter
  8999. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9000. }
  9001. img.src = blobURL;
  9002. usingObjectURL = true;
  9003. }
  9004. catch (e) {
  9005. img.src = "";
  9006. }
  9007. return img;
  9008. }
  9009. }
  9010. noIndexedDB();
  9011. }
  9012. return img;
  9013. };
  9014. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9015. url = Tools.CleanUrl(url);
  9016. url = Tools.PreprocessUrl(url);
  9017. // If file and file input are set
  9018. if (url.indexOf("file:") !== -1) {
  9019. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9020. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9021. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9022. }
  9023. }
  9024. var loadUrl = Tools.BaseUrl + url;
  9025. var aborted = false;
  9026. var fileRequest = {
  9027. onCompleteObservable: new BABYLON.Observable(),
  9028. abort: function () { return aborted = true; },
  9029. };
  9030. var requestFile = function () {
  9031. var request = new XMLHttpRequest();
  9032. var retryHandle = null;
  9033. fileRequest.abort = function () {
  9034. aborted = true;
  9035. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9036. request.abort();
  9037. }
  9038. if (retryHandle !== null) {
  9039. clearTimeout(retryHandle);
  9040. retryHandle = null;
  9041. }
  9042. };
  9043. var retryLoop = function (retryIndex) {
  9044. request.open('GET', loadUrl, true);
  9045. if (useArrayBuffer) {
  9046. request.responseType = "arraybuffer";
  9047. }
  9048. if (onProgress) {
  9049. request.addEventListener("progress", onProgress);
  9050. }
  9051. var onLoadEnd = function () {
  9052. request.removeEventListener("loadend", onLoadEnd);
  9053. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9054. fileRequest.onCompleteObservable.clear();
  9055. };
  9056. request.addEventListener("loadend", onLoadEnd);
  9057. var onReadyStateChange = function () {
  9058. if (aborted) {
  9059. return;
  9060. }
  9061. // In case of undefined state in some browsers.
  9062. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9063. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9064. request.removeEventListener("readystatechange", onReadyStateChange);
  9065. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9066. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9067. return;
  9068. }
  9069. var retryStrategy = Tools.DefaultRetryStrategy;
  9070. if (retryStrategy) {
  9071. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9072. if (waitTime !== -1) {
  9073. // Prevent the request from completing for retry.
  9074. request.removeEventListener("loadend", onLoadEnd);
  9075. request = new XMLHttpRequest();
  9076. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9077. return;
  9078. }
  9079. }
  9080. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9081. if (onError) {
  9082. onError(request, e);
  9083. }
  9084. else {
  9085. throw e;
  9086. }
  9087. }
  9088. };
  9089. request.addEventListener("readystatechange", onReadyStateChange);
  9090. request.send();
  9091. };
  9092. retryLoop(0);
  9093. };
  9094. // Caching all files
  9095. if (database && database.enableSceneOffline) {
  9096. var noIndexedDB_1 = function (request) {
  9097. if (request && request.status > 400) {
  9098. if (onError) {
  9099. onError(request);
  9100. }
  9101. }
  9102. else {
  9103. if (!aborted) {
  9104. requestFile();
  9105. }
  9106. }
  9107. };
  9108. var loadFromIndexedDB = function () {
  9109. // TODO: database needs to support aborting and should return a IFileRequest
  9110. if (aborted) {
  9111. return;
  9112. }
  9113. if (database) {
  9114. database.loadFileFromDB(url, function (data) {
  9115. if (!aborted) {
  9116. onSuccess(data);
  9117. }
  9118. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9119. }, onProgress ? function (event) {
  9120. if (!aborted) {
  9121. onProgress(event);
  9122. }
  9123. } : undefined, noIndexedDB_1, useArrayBuffer);
  9124. }
  9125. };
  9126. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9127. }
  9128. else {
  9129. requestFile();
  9130. }
  9131. return fileRequest;
  9132. };
  9133. /**
  9134. * Load a script (identified by an url). When the url returns, the
  9135. * content of this file is added into a new script element, attached to the DOM (body element)
  9136. */
  9137. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9138. var head = document.getElementsByTagName('head')[0];
  9139. var script = document.createElement('script');
  9140. script.type = 'text/javascript';
  9141. script.src = scriptUrl;
  9142. script.onload = function () {
  9143. if (onSuccess) {
  9144. onSuccess();
  9145. }
  9146. };
  9147. script.onerror = function (e) {
  9148. if (onError) {
  9149. onError("Unable to load script '" + scriptUrl + "'", e);
  9150. }
  9151. };
  9152. head.appendChild(script);
  9153. };
  9154. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9155. var reader = new FileReader();
  9156. var request = {
  9157. onCompleteObservable: new BABYLON.Observable(),
  9158. abort: function () { return reader.abort(); },
  9159. };
  9160. reader.onloadend = function (e) {
  9161. request.onCompleteObservable.notifyObservers(request);
  9162. };
  9163. reader.onload = function (e) {
  9164. //target doesn't have result from ts 1.3
  9165. callback(e.target['result']);
  9166. };
  9167. reader.onprogress = progressCallback;
  9168. reader.readAsDataURL(fileToLoad);
  9169. return request;
  9170. };
  9171. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9172. var reader = new FileReader();
  9173. var request = {
  9174. onCompleteObservable: new BABYLON.Observable(),
  9175. abort: function () { return reader.abort(); },
  9176. };
  9177. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9178. reader.onerror = function (e) {
  9179. Tools.Log("Error while reading file: " + fileToLoad.name);
  9180. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9181. };
  9182. reader.onload = function (e) {
  9183. //target doesn't have result from ts 1.3
  9184. callback(e.target['result']);
  9185. };
  9186. if (progressCallBack) {
  9187. reader.onprogress = progressCallBack;
  9188. }
  9189. if (!useArrayBuffer) {
  9190. // Asynchronous read
  9191. reader.readAsText(fileToLoad);
  9192. }
  9193. else {
  9194. reader.readAsArrayBuffer(fileToLoad);
  9195. }
  9196. return request;
  9197. };
  9198. //returns a downloadable url to a file content.
  9199. Tools.FileAsURL = function (content) {
  9200. var fileBlob = new Blob([content]);
  9201. var url = window.URL || window.webkitURL;
  9202. var link = url.createObjectURL(fileBlob);
  9203. return link;
  9204. };
  9205. // Misc.
  9206. Tools.Format = function (value, decimals) {
  9207. if (decimals === void 0) { decimals = 2; }
  9208. return value.toFixed(decimals);
  9209. };
  9210. Tools.CheckExtends = function (v, min, max) {
  9211. if (v.x < min.x)
  9212. min.x = v.x;
  9213. if (v.y < min.y)
  9214. min.y = v.y;
  9215. if (v.z < min.z)
  9216. min.z = v.z;
  9217. if (v.x > max.x)
  9218. max.x = v.x;
  9219. if (v.y > max.y)
  9220. max.y = v.y;
  9221. if (v.z > max.z)
  9222. max.z = v.z;
  9223. };
  9224. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9225. for (var prop in source) {
  9226. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9227. continue;
  9228. }
  9229. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9230. continue;
  9231. }
  9232. var sourceValue = source[prop];
  9233. var typeOfSourceValue = typeof sourceValue;
  9234. if (typeOfSourceValue === "function") {
  9235. continue;
  9236. }
  9237. try {
  9238. if (typeOfSourceValue === "object") {
  9239. if (sourceValue instanceof Array) {
  9240. destination[prop] = [];
  9241. if (sourceValue.length > 0) {
  9242. if (typeof sourceValue[0] == "object") {
  9243. for (var index = 0; index < sourceValue.length; index++) {
  9244. var clonedValue = cloneValue(sourceValue[index], destination);
  9245. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9246. destination[prop].push(clonedValue);
  9247. }
  9248. }
  9249. }
  9250. else {
  9251. destination[prop] = sourceValue.slice(0);
  9252. }
  9253. }
  9254. }
  9255. else {
  9256. destination[prop] = cloneValue(sourceValue, destination);
  9257. }
  9258. }
  9259. else {
  9260. destination[prop] = sourceValue;
  9261. }
  9262. }
  9263. catch (e) {
  9264. // Just ignore error (it could be because of a read-only property)
  9265. }
  9266. }
  9267. };
  9268. Tools.IsEmpty = function (obj) {
  9269. for (var i in obj) {
  9270. if (obj.hasOwnProperty(i)) {
  9271. return false;
  9272. }
  9273. }
  9274. return true;
  9275. };
  9276. Tools.RegisterTopRootEvents = function (events) {
  9277. for (var index = 0; index < events.length; index++) {
  9278. var event = events[index];
  9279. window.addEventListener(event.name, event.handler, false);
  9280. try {
  9281. if (window.parent) {
  9282. window.parent.addEventListener(event.name, event.handler, false);
  9283. }
  9284. }
  9285. catch (e) {
  9286. // Silently fails...
  9287. }
  9288. }
  9289. };
  9290. Tools.UnregisterTopRootEvents = function (events) {
  9291. for (var index = 0; index < events.length; index++) {
  9292. var event = events[index];
  9293. window.removeEventListener(event.name, event.handler);
  9294. try {
  9295. if (window.parent) {
  9296. window.parent.removeEventListener(event.name, event.handler);
  9297. }
  9298. }
  9299. catch (e) {
  9300. // Silently fails...
  9301. }
  9302. }
  9303. };
  9304. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9305. if (mimeType === void 0) { mimeType = "image/png"; }
  9306. // Read the contents of the framebuffer
  9307. var numberOfChannelsByLine = width * 4;
  9308. var halfHeight = height / 2;
  9309. //Reading datas from WebGL
  9310. var data = engine.readPixels(0, 0, width, height);
  9311. //To flip image on Y axis.
  9312. for (var i = 0; i < halfHeight; i++) {
  9313. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9314. var currentCell = j + i * numberOfChannelsByLine;
  9315. var targetLine = height - i - 1;
  9316. var targetCell = j + targetLine * numberOfChannelsByLine;
  9317. var temp = data[currentCell];
  9318. data[currentCell] = data[targetCell];
  9319. data[targetCell] = temp;
  9320. }
  9321. }
  9322. // Create a 2D canvas to store the result
  9323. if (!screenshotCanvas) {
  9324. screenshotCanvas = document.createElement('canvas');
  9325. }
  9326. screenshotCanvas.width = width;
  9327. screenshotCanvas.height = height;
  9328. var context = screenshotCanvas.getContext('2d');
  9329. if (context) {
  9330. // Copy the pixels to a 2D canvas
  9331. var imageData = context.createImageData(width, height);
  9332. var castData = (imageData.data);
  9333. castData.set(data);
  9334. context.putImageData(imageData, 0, 0);
  9335. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9336. }
  9337. };
  9338. /**
  9339. * Converts the canvas data to blob.
  9340. * This acts as a polyfill for browsers not supporting the to blob function.
  9341. * @param canvas Defines the canvas to extract the data from
  9342. * @param successCallback Defines the callback triggered once the data are available
  9343. * @param mimeType Defines the mime type of the result
  9344. */
  9345. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9346. if (mimeType === void 0) { mimeType = "image/png"; }
  9347. // We need HTMLCanvasElement.toBlob for HD screenshots
  9348. if (!canvas.toBlob) {
  9349. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9350. canvas.toBlob = function (callback, type, quality) {
  9351. var _this = this;
  9352. setTimeout(function () {
  9353. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9354. for (var i = 0; i < len; i++) {
  9355. arr[i] = binStr.charCodeAt(i);
  9356. }
  9357. callback(new Blob([arr]));
  9358. });
  9359. };
  9360. }
  9361. canvas.toBlob(function (blob) {
  9362. successCallback(blob);
  9363. }, mimeType);
  9364. };
  9365. /**
  9366. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9367. * @param successCallback Defines the callback triggered once the data are available
  9368. * @param mimeType Defines the mime type of the result
  9369. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9370. */
  9371. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9372. if (mimeType === void 0) { mimeType = "image/png"; }
  9373. if (successCallback) {
  9374. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9375. successCallback(base64Image);
  9376. }
  9377. else {
  9378. this.ToBlob(screenshotCanvas, function (blob) {
  9379. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9380. if (("download" in document.createElement("a"))) {
  9381. if (!fileName) {
  9382. var date = new Date();
  9383. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9384. fileName = "screenshot_" + stringDate + ".png";
  9385. }
  9386. Tools.Download(blob, fileName);
  9387. }
  9388. else {
  9389. var url = URL.createObjectURL(blob);
  9390. var newWindow = window.open("");
  9391. if (!newWindow)
  9392. return;
  9393. var img = newWindow.document.createElement("img");
  9394. img.onload = function () {
  9395. // no longer need to read the blob so it's revoked
  9396. URL.revokeObjectURL(url);
  9397. };
  9398. img.src = url;
  9399. newWindow.document.body.appendChild(img);
  9400. }
  9401. }, mimeType);
  9402. }
  9403. };
  9404. /**
  9405. * Downloads a blob in the browser
  9406. * @param blob defines the blob to download
  9407. * @param fileName defines the name of the downloaded file
  9408. */
  9409. Tools.Download = function (blob, fileName) {
  9410. var url = window.URL.createObjectURL(blob);
  9411. var a = document.createElement("a");
  9412. document.body.appendChild(a);
  9413. a.style.display = "none";
  9414. a.href = url;
  9415. a.download = fileName;
  9416. a.addEventListener("click", function () {
  9417. if (a.parentElement) {
  9418. a.parentElement.removeChild(a);
  9419. }
  9420. });
  9421. a.click();
  9422. window.URL.revokeObjectURL(url);
  9423. };
  9424. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9425. if (mimeType === void 0) { mimeType = "image/png"; }
  9426. var width;
  9427. var height;
  9428. // If a precision value is specified
  9429. if (size.precision) {
  9430. width = Math.round(engine.getRenderWidth() * size.precision);
  9431. height = Math.round(width / engine.getAspectRatio(camera));
  9432. }
  9433. else if (size.width && size.height) {
  9434. width = size.width;
  9435. height = size.height;
  9436. }
  9437. //If passing only width, computing height to keep display canvas ratio.
  9438. else if (size.width && !size.height) {
  9439. width = size.width;
  9440. height = Math.round(width / engine.getAspectRatio(camera));
  9441. }
  9442. //If passing only height, computing width to keep display canvas ratio.
  9443. else if (size.height && !size.width) {
  9444. height = size.height;
  9445. width = Math.round(height * engine.getAspectRatio(camera));
  9446. }
  9447. //Assuming here that "size" parameter is a number
  9448. else if (!isNaN(size)) {
  9449. height = size;
  9450. width = size;
  9451. }
  9452. else {
  9453. Tools.Error("Invalid 'size' parameter !");
  9454. return;
  9455. }
  9456. if (!screenshotCanvas) {
  9457. screenshotCanvas = document.createElement('canvas');
  9458. }
  9459. screenshotCanvas.width = width;
  9460. screenshotCanvas.height = height;
  9461. var renderContext = screenshotCanvas.getContext("2d");
  9462. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9463. var newWidth = width;
  9464. var newHeight = newWidth / ratio;
  9465. if (newHeight > height) {
  9466. newHeight = height;
  9467. newWidth = newHeight * ratio;
  9468. }
  9469. var offsetX = Math.max(0, width - newWidth) / 2;
  9470. var offsetY = Math.max(0, height - newHeight) / 2;
  9471. var renderingCanvas = engine.getRenderingCanvas();
  9472. if (renderContext && renderingCanvas) {
  9473. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9474. }
  9475. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9476. };
  9477. /**
  9478. * Generates an image screenshot from the specified camera.
  9479. *
  9480. * @param engine The engine to use for rendering
  9481. * @param camera The camera to use for rendering
  9482. * @param size This parameter can be set to a single number or to an object with the
  9483. * following (optional) properties: precision, width, height. If a single number is passed,
  9484. * it will be used for both width and height. If an object is passed, the screenshot size
  9485. * will be derived from the parameters. The precision property is a multiplier allowing
  9486. * rendering at a higher or lower resolution.
  9487. * @param successCallback The callback receives a single parameter which contains the
  9488. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9489. * src parameter of an <img> to display it.
  9490. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9491. * Check your browser for supported MIME types.
  9492. * @param samples Texture samples (default: 1)
  9493. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9494. * @param fileName A name for for the downloaded file.
  9495. * @constructor
  9496. */
  9497. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9498. if (mimeType === void 0) { mimeType = "image/png"; }
  9499. if (samples === void 0) { samples = 1; }
  9500. if (antialiasing === void 0) { antialiasing = false; }
  9501. var width;
  9502. var height;
  9503. //If a precision value is specified
  9504. if (size.precision) {
  9505. width = Math.round(engine.getRenderWidth() * size.precision);
  9506. height = Math.round(width / engine.getAspectRatio(camera));
  9507. size = { width: width, height: height };
  9508. }
  9509. else if (size.width && size.height) {
  9510. width = size.width;
  9511. height = size.height;
  9512. }
  9513. //If passing only width, computing height to keep display canvas ratio.
  9514. else if (size.width && !size.height) {
  9515. width = size.width;
  9516. height = Math.round(width / engine.getAspectRatio(camera));
  9517. size = { width: width, height: height };
  9518. }
  9519. //If passing only height, computing width to keep display canvas ratio.
  9520. else if (size.height && !size.width) {
  9521. height = size.height;
  9522. width = Math.round(height * engine.getAspectRatio(camera));
  9523. size = { width: width, height: height };
  9524. }
  9525. //Assuming here that "size" parameter is a number
  9526. else if (!isNaN(size)) {
  9527. height = size;
  9528. width = size;
  9529. }
  9530. else {
  9531. Tools.Error("Invalid 'size' parameter !");
  9532. return;
  9533. }
  9534. var scene = camera.getScene();
  9535. var previousCamera = null;
  9536. if (scene.activeCamera !== camera) {
  9537. previousCamera = scene.activeCamera;
  9538. scene.activeCamera = camera;
  9539. }
  9540. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9541. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9542. texture.renderList = null;
  9543. texture.samples = samples;
  9544. if (antialiasing) {
  9545. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9546. }
  9547. texture.onAfterRenderObservable.add(function () {
  9548. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9549. });
  9550. scene.incrementRenderId();
  9551. scene.resetCachedMaterial();
  9552. texture.render(true);
  9553. texture.dispose();
  9554. if (previousCamera) {
  9555. scene.activeCamera = previousCamera;
  9556. }
  9557. camera.getProjectionMatrix(true); // Force cache refresh;
  9558. };
  9559. // XHR response validator for local file scenario
  9560. Tools.ValidateXHRData = function (xhr, dataType) {
  9561. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9562. if (dataType === void 0) { dataType = 7; }
  9563. try {
  9564. if (dataType & 1) {
  9565. if (xhr.responseText && xhr.responseText.length > 0) {
  9566. return true;
  9567. }
  9568. else if (dataType === 1) {
  9569. return false;
  9570. }
  9571. }
  9572. if (dataType & 2) {
  9573. // Check header width and height since there is no "TGA" magic number
  9574. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9575. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9576. return true;
  9577. }
  9578. else if (dataType === 2) {
  9579. return false;
  9580. }
  9581. }
  9582. if (dataType & 4) {
  9583. // Check for the "DDS" magic number
  9584. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9585. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9586. return true;
  9587. }
  9588. else {
  9589. return false;
  9590. }
  9591. }
  9592. }
  9593. catch (e) {
  9594. // Global protection
  9595. }
  9596. return false;
  9597. };
  9598. /**
  9599. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9600. * Be aware Math.random() could cause collisions, but:
  9601. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  9602. */
  9603. Tools.RandomId = function () {
  9604. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9605. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9606. return v.toString(16);
  9607. });
  9608. };
  9609. /**
  9610. * Test if the given uri is a base64 string.
  9611. * @param uri The uri to test
  9612. * @return True if the uri is a base64 string or false otherwise.
  9613. */
  9614. Tools.IsBase64 = function (uri) {
  9615. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9616. };
  9617. /**
  9618. * Decode the given base64 uri.
  9619. * @param uri The uri to decode
  9620. * @return The decoded base64 data.
  9621. */
  9622. Tools.DecodeBase64 = function (uri) {
  9623. var decodedString = atob(uri.split(",")[1]);
  9624. var bufferLength = decodedString.length;
  9625. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9626. for (var i = 0; i < bufferLength; i++) {
  9627. bufferView[i] = decodedString.charCodeAt(i);
  9628. }
  9629. return bufferView.buffer;
  9630. };
  9631. Object.defineProperty(Tools, "NoneLogLevel", {
  9632. get: function () {
  9633. return Tools._NoneLogLevel;
  9634. },
  9635. enumerable: true,
  9636. configurable: true
  9637. });
  9638. Object.defineProperty(Tools, "MessageLogLevel", {
  9639. get: function () {
  9640. return Tools._MessageLogLevel;
  9641. },
  9642. enumerable: true,
  9643. configurable: true
  9644. });
  9645. Object.defineProperty(Tools, "WarningLogLevel", {
  9646. get: function () {
  9647. return Tools._WarningLogLevel;
  9648. },
  9649. enumerable: true,
  9650. configurable: true
  9651. });
  9652. Object.defineProperty(Tools, "ErrorLogLevel", {
  9653. get: function () {
  9654. return Tools._ErrorLogLevel;
  9655. },
  9656. enumerable: true,
  9657. configurable: true
  9658. });
  9659. Object.defineProperty(Tools, "AllLogLevel", {
  9660. get: function () {
  9661. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9662. },
  9663. enumerable: true,
  9664. configurable: true
  9665. });
  9666. Tools._AddLogEntry = function (entry) {
  9667. Tools._LogCache = entry + Tools._LogCache;
  9668. if (Tools.OnNewCacheEntry) {
  9669. Tools.OnNewCacheEntry(entry);
  9670. }
  9671. };
  9672. Tools._FormatMessage = function (message) {
  9673. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9674. var date = new Date();
  9675. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9676. };
  9677. Tools._LogDisabled = function (message) {
  9678. // nothing to do
  9679. };
  9680. Tools._LogEnabled = function (message) {
  9681. var formattedMessage = Tools._FormatMessage(message);
  9682. console.log("BJS - " + formattedMessage);
  9683. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9684. Tools._AddLogEntry(entry);
  9685. };
  9686. Tools._WarnDisabled = function (message) {
  9687. // nothing to do
  9688. };
  9689. Tools._WarnEnabled = function (message) {
  9690. var formattedMessage = Tools._FormatMessage(message);
  9691. console.warn("BJS - " + formattedMessage);
  9692. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9693. Tools._AddLogEntry(entry);
  9694. };
  9695. Tools._ErrorDisabled = function (message) {
  9696. // nothing to do
  9697. };
  9698. Tools._ErrorEnabled = function (message) {
  9699. Tools.errorsCount++;
  9700. var formattedMessage = Tools._FormatMessage(message);
  9701. console.error("BJS - " + formattedMessage);
  9702. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9703. Tools._AddLogEntry(entry);
  9704. };
  9705. Object.defineProperty(Tools, "LogCache", {
  9706. get: function () {
  9707. return Tools._LogCache;
  9708. },
  9709. enumerable: true,
  9710. configurable: true
  9711. });
  9712. Tools.ClearLogCache = function () {
  9713. Tools._LogCache = "";
  9714. Tools.errorsCount = 0;
  9715. };
  9716. Object.defineProperty(Tools, "LogLevels", {
  9717. set: function (level) {
  9718. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9719. Tools.Log = Tools._LogEnabled;
  9720. }
  9721. else {
  9722. Tools.Log = Tools._LogDisabled;
  9723. }
  9724. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9725. Tools.Warn = Tools._WarnEnabled;
  9726. }
  9727. else {
  9728. Tools.Warn = Tools._WarnDisabled;
  9729. }
  9730. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9731. Tools.Error = Tools._ErrorEnabled;
  9732. }
  9733. else {
  9734. Tools.Error = Tools._ErrorDisabled;
  9735. }
  9736. },
  9737. enumerable: true,
  9738. configurable: true
  9739. });
  9740. Tools.IsWindowObjectExist = function () {
  9741. return (typeof window) !== "undefined";
  9742. };
  9743. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9744. get: function () {
  9745. return Tools._PerformanceNoneLogLevel;
  9746. },
  9747. enumerable: true,
  9748. configurable: true
  9749. });
  9750. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9751. get: function () {
  9752. return Tools._PerformanceUserMarkLogLevel;
  9753. },
  9754. enumerable: true,
  9755. configurable: true
  9756. });
  9757. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9758. get: function () {
  9759. return Tools._PerformanceConsoleLogLevel;
  9760. },
  9761. enumerable: true,
  9762. configurable: true
  9763. });
  9764. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9765. set: function (level) {
  9766. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9767. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9768. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9769. return;
  9770. }
  9771. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9772. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9773. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9774. return;
  9775. }
  9776. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9777. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9778. },
  9779. enumerable: true,
  9780. configurable: true
  9781. });
  9782. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9783. };
  9784. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9785. };
  9786. Tools._StartUserMark = function (counterName, condition) {
  9787. if (condition === void 0) { condition = true; }
  9788. if (!Tools._performance) {
  9789. if (!Tools.IsWindowObjectExist()) {
  9790. return;
  9791. }
  9792. Tools._performance = window.performance;
  9793. }
  9794. if (!condition || !Tools._performance.mark) {
  9795. return;
  9796. }
  9797. Tools._performance.mark(counterName + "-Begin");
  9798. };
  9799. Tools._EndUserMark = function (counterName, condition) {
  9800. if (condition === void 0) { condition = true; }
  9801. if (!condition || !Tools._performance.mark) {
  9802. return;
  9803. }
  9804. Tools._performance.mark(counterName + "-End");
  9805. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9806. };
  9807. Tools._StartPerformanceConsole = function (counterName, condition) {
  9808. if (condition === void 0) { condition = true; }
  9809. if (!condition) {
  9810. return;
  9811. }
  9812. Tools._StartUserMark(counterName, condition);
  9813. if (console.time) {
  9814. console.time(counterName);
  9815. }
  9816. };
  9817. Tools._EndPerformanceConsole = function (counterName, condition) {
  9818. if (condition === void 0) { condition = true; }
  9819. if (!condition) {
  9820. return;
  9821. }
  9822. Tools._EndUserMark(counterName, condition);
  9823. if (console.time) {
  9824. console.timeEnd(counterName);
  9825. }
  9826. };
  9827. Object.defineProperty(Tools, "Now", {
  9828. get: function () {
  9829. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9830. return window.performance.now();
  9831. }
  9832. return Date.now();
  9833. },
  9834. enumerable: true,
  9835. configurable: true
  9836. });
  9837. /**
  9838. * This method will return the name of the class used to create the instance of the given object.
  9839. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9840. * @param object the object to get the class name from
  9841. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9842. */
  9843. Tools.GetClassName = function (object, isType) {
  9844. if (isType === void 0) { isType = false; }
  9845. var name = null;
  9846. if (!isType && object.getClassName) {
  9847. name = object.getClassName();
  9848. }
  9849. else {
  9850. if (object instanceof Object) {
  9851. var classObj = isType ? object : Object.getPrototypeOf(object);
  9852. name = classObj.constructor["__bjsclassName__"];
  9853. }
  9854. if (!name) {
  9855. name = typeof object;
  9856. }
  9857. }
  9858. return name;
  9859. };
  9860. Tools.First = function (array, predicate) {
  9861. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9862. var el = array_1[_i];
  9863. if (predicate(el)) {
  9864. return el;
  9865. }
  9866. }
  9867. return null;
  9868. };
  9869. /**
  9870. * This method will return the name of the full name of the class, including its owning module (if any).
  9871. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  9872. * @param object the object to get the class name from
  9873. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  9874. */
  9875. Tools.getFullClassName = function (object, isType) {
  9876. if (isType === void 0) { isType = false; }
  9877. var className = null;
  9878. var moduleName = null;
  9879. if (!isType && object.getClassName) {
  9880. className = object.getClassName();
  9881. }
  9882. else {
  9883. if (object instanceof Object) {
  9884. var classObj = isType ? object : Object.getPrototypeOf(object);
  9885. className = classObj.constructor["__bjsclassName__"];
  9886. moduleName = classObj.constructor["__bjsmoduleName__"];
  9887. }
  9888. if (!className) {
  9889. className = typeof object;
  9890. }
  9891. }
  9892. if (!className) {
  9893. return null;
  9894. }
  9895. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9896. };
  9897. /**
  9898. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  9899. * @param array
  9900. */
  9901. Tools.arrayOrStringFeeder = function (array) {
  9902. return function (index) {
  9903. if (index >= array.length) {
  9904. return null;
  9905. }
  9906. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9907. if (val && val.getHashCode) {
  9908. val = val.getHashCode();
  9909. }
  9910. if (typeof val === "string") {
  9911. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9912. }
  9913. return val;
  9914. };
  9915. };
  9916. /**
  9917. * Compute the hashCode of a stream of number
  9918. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9919. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9920. * @return the hash code computed
  9921. */
  9922. Tools.hashCodeFromStream = function (feeder) {
  9923. // Based from here: http://stackoverflow.com/a/7616484/802124
  9924. var hash = 0;
  9925. var index = 0;
  9926. var chr = feeder(index++);
  9927. while (chr != null) {
  9928. hash = ((hash << 5) - hash) + chr;
  9929. hash |= 0; // Convert to 32bit integer
  9930. chr = feeder(index++);
  9931. }
  9932. return hash;
  9933. };
  9934. /**
  9935. * Returns a promise that resolves after the given amount of time.
  9936. * @param delay Number of milliseconds to delay
  9937. * @returns Promise that resolves after the given amount of time
  9938. */
  9939. Tools.DelayAsync = function (delay) {
  9940. return new Promise(function (resolve) {
  9941. setTimeout(function () {
  9942. resolve();
  9943. }, delay);
  9944. });
  9945. };
  9946. /**
  9947. * Gets the current gradient from an array of IValueGradient
  9948. * @param ratio defines the current ratio to get
  9949. * @param gradients defines the array of IValueGradient
  9950. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  9951. */
  9952. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  9953. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  9954. var currentGradient = gradients[gradientIndex];
  9955. var nextGradient = gradients[gradientIndex + 1];
  9956. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  9957. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  9958. updateFunc(currentGradient, nextGradient, scale);
  9959. }
  9960. }
  9961. };
  9962. Tools.BaseUrl = "";
  9963. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9964. /**
  9965. * Default behaviour for cors in the application.
  9966. * It can be a string if the expected behavior is identical in the entire app.
  9967. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9968. */
  9969. Tools.CorsBehavior = "anonymous";
  9970. Tools.UseFallbackTexture = true;
  9971. /**
  9972. * Use this object to register external classes like custom textures or material
  9973. * to allow the laoders to instantiate them
  9974. */
  9975. Tools.RegisteredExternalClasses = {};
  9976. // Used in case of a texture loading problem
  9977. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  9978. Tools._tmpFloatArray = new Float32Array(1);
  9979. Tools.PreprocessUrl = function (url) {
  9980. return url;
  9981. };
  9982. // Logs
  9983. Tools._NoneLogLevel = 0;
  9984. Tools._MessageLogLevel = 1;
  9985. Tools._WarningLogLevel = 2;
  9986. Tools._ErrorLogLevel = 4;
  9987. Tools._LogCache = "";
  9988. Tools.errorsCount = 0;
  9989. Tools.Log = Tools._LogEnabled;
  9990. Tools.Warn = Tools._WarnEnabled;
  9991. Tools.Error = Tools._ErrorEnabled;
  9992. // Performances
  9993. Tools._PerformanceNoneLogLevel = 0;
  9994. Tools._PerformanceUserMarkLogLevel = 1;
  9995. Tools._PerformanceConsoleLogLevel = 2;
  9996. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9997. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9998. return Tools;
  9999. }());
  10000. BABYLON.Tools = Tools;
  10001. /**
  10002. * This class is used to track a performance counter which is number based.
  10003. * The user has access to many properties which give statistics of different nature
  10004. *
  10005. * The implementer can track two kinds of Performance Counter: time and count
  10006. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  10007. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  10008. */
  10009. var PerfCounter = /** @class */ (function () {
  10010. function PerfCounter() {
  10011. this._startMonitoringTime = 0;
  10012. this._min = 0;
  10013. this._max = 0;
  10014. this._average = 0;
  10015. this._lastSecAverage = 0;
  10016. this._current = 0;
  10017. this._totalValueCount = 0;
  10018. this._totalAccumulated = 0;
  10019. this._lastSecAccumulated = 0;
  10020. this._lastSecTime = 0;
  10021. this._lastSecValueCount = 0;
  10022. }
  10023. Object.defineProperty(PerfCounter.prototype, "min", {
  10024. /**
  10025. * Returns the smallest value ever
  10026. */
  10027. get: function () {
  10028. return this._min;
  10029. },
  10030. enumerable: true,
  10031. configurable: true
  10032. });
  10033. Object.defineProperty(PerfCounter.prototype, "max", {
  10034. /**
  10035. * Returns the biggest value ever
  10036. */
  10037. get: function () {
  10038. return this._max;
  10039. },
  10040. enumerable: true,
  10041. configurable: true
  10042. });
  10043. Object.defineProperty(PerfCounter.prototype, "average", {
  10044. /**
  10045. * Returns the average value since the performance counter is running
  10046. */
  10047. get: function () {
  10048. return this._average;
  10049. },
  10050. enumerable: true,
  10051. configurable: true
  10052. });
  10053. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10054. /**
  10055. * Returns the average value of the last second the counter was monitored
  10056. */
  10057. get: function () {
  10058. return this._lastSecAverage;
  10059. },
  10060. enumerable: true,
  10061. configurable: true
  10062. });
  10063. Object.defineProperty(PerfCounter.prototype, "current", {
  10064. /**
  10065. * Returns the current value
  10066. */
  10067. get: function () {
  10068. return this._current;
  10069. },
  10070. enumerable: true,
  10071. configurable: true
  10072. });
  10073. Object.defineProperty(PerfCounter.prototype, "total", {
  10074. get: function () {
  10075. return this._totalAccumulated;
  10076. },
  10077. enumerable: true,
  10078. configurable: true
  10079. });
  10080. Object.defineProperty(PerfCounter.prototype, "count", {
  10081. get: function () {
  10082. return this._totalValueCount;
  10083. },
  10084. enumerable: true,
  10085. configurable: true
  10086. });
  10087. /**
  10088. * Call this method to start monitoring a new frame.
  10089. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  10090. */
  10091. PerfCounter.prototype.fetchNewFrame = function () {
  10092. this._totalValueCount++;
  10093. this._current = 0;
  10094. this._lastSecValueCount++;
  10095. };
  10096. /**
  10097. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10098. * @param newCount the count value to add to the monitored count
  10099. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  10100. */
  10101. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10102. if (!PerfCounter.Enabled) {
  10103. return;
  10104. }
  10105. this._current += newCount;
  10106. if (fetchResult) {
  10107. this._fetchResult();
  10108. }
  10109. };
  10110. /**
  10111. * Start monitoring this performance counter
  10112. */
  10113. PerfCounter.prototype.beginMonitoring = function () {
  10114. if (!PerfCounter.Enabled) {
  10115. return;
  10116. }
  10117. this._startMonitoringTime = Tools.Now;
  10118. };
  10119. /**
  10120. * Compute the time lapsed since the previous beginMonitoring() call.
  10121. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  10122. */
  10123. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10124. if (newFrame === void 0) { newFrame = true; }
  10125. if (!PerfCounter.Enabled) {
  10126. return;
  10127. }
  10128. if (newFrame) {
  10129. this.fetchNewFrame();
  10130. }
  10131. var currentTime = Tools.Now;
  10132. this._current = currentTime - this._startMonitoringTime;
  10133. if (newFrame) {
  10134. this._fetchResult();
  10135. }
  10136. };
  10137. PerfCounter.prototype._fetchResult = function () {
  10138. this._totalAccumulated += this._current;
  10139. this._lastSecAccumulated += this._current;
  10140. // Min/Max update
  10141. this._min = Math.min(this._min, this._current);
  10142. this._max = Math.max(this._max, this._current);
  10143. this._average = this._totalAccumulated / this._totalValueCount;
  10144. // Reset last sec?
  10145. var now = Tools.Now;
  10146. if ((now - this._lastSecTime) > 1000) {
  10147. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10148. this._lastSecTime = now;
  10149. this._lastSecAccumulated = 0;
  10150. this._lastSecValueCount = 0;
  10151. }
  10152. };
  10153. PerfCounter.Enabled = true;
  10154. return PerfCounter;
  10155. }());
  10156. BABYLON.PerfCounter = PerfCounter;
  10157. /**
  10158. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10159. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10160. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10161. * @param name The name of the class, case should be preserved
  10162. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10163. */
  10164. function className(name, module) {
  10165. return function (target) {
  10166. target["__bjsclassName__"] = name;
  10167. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10168. };
  10169. }
  10170. BABYLON.className = className;
  10171. /**
  10172. * An implementation of a loop for asynchronous functions.
  10173. */
  10174. var AsyncLoop = /** @class */ (function () {
  10175. /**
  10176. * Constroctor.
  10177. * @param iterations the number of iterations.
  10178. * @param _fn the function to run each iteration
  10179. * @param _successCallback the callback that will be called upon succesful execution
  10180. * @param offset starting offset.
  10181. */
  10182. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10183. if (offset === void 0) { offset = 0; }
  10184. this.iterations = iterations;
  10185. this._fn = _fn;
  10186. this._successCallback = _successCallback;
  10187. this.index = offset - 1;
  10188. this._done = false;
  10189. }
  10190. /**
  10191. * Execute the next iteration. Must be called after the last iteration was finished.
  10192. */
  10193. AsyncLoop.prototype.executeNext = function () {
  10194. if (!this._done) {
  10195. if (this.index + 1 < this.iterations) {
  10196. ++this.index;
  10197. this._fn(this);
  10198. }
  10199. else {
  10200. this.breakLoop();
  10201. }
  10202. }
  10203. };
  10204. /**
  10205. * Break the loop and run the success callback.
  10206. */
  10207. AsyncLoop.prototype.breakLoop = function () {
  10208. this._done = true;
  10209. this._successCallback();
  10210. };
  10211. /**
  10212. * Helper function
  10213. */
  10214. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10215. if (offset === void 0) { offset = 0; }
  10216. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10217. loop.executeNext();
  10218. return loop;
  10219. };
  10220. /**
  10221. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10222. * @param iterations total number of iterations
  10223. * @param syncedIterations number of synchronous iterations in each async iteration.
  10224. * @param fn the function to call each iteration.
  10225. * @param callback a success call back that will be called when iterating stops.
  10226. * @param breakFunction a break condition (optional)
  10227. * @param timeout timeout settings for the setTimeout function. default - 0.
  10228. * @constructor
  10229. */
  10230. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10231. if (timeout === void 0) { timeout = 0; }
  10232. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10233. if (breakFunction && breakFunction())
  10234. loop.breakLoop();
  10235. else {
  10236. setTimeout(function () {
  10237. for (var i = 0; i < syncedIterations; ++i) {
  10238. var iteration = (loop.index * syncedIterations) + i;
  10239. if (iteration >= iterations)
  10240. break;
  10241. fn(iteration);
  10242. if (breakFunction && breakFunction()) {
  10243. loop.breakLoop();
  10244. break;
  10245. }
  10246. }
  10247. loop.executeNext();
  10248. }, timeout);
  10249. }
  10250. }, callback);
  10251. };
  10252. return AsyncLoop;
  10253. }());
  10254. BABYLON.AsyncLoop = AsyncLoop;
  10255. })(BABYLON || (BABYLON = {}));
  10256. //# sourceMappingURL=babylon.tools.js.map
  10257. var BABYLON;
  10258. (function (BABYLON) {
  10259. var PromiseStates;
  10260. (function (PromiseStates) {
  10261. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10262. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10263. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10264. })(PromiseStates || (PromiseStates = {}));
  10265. var FulFillmentAgregator = /** @class */ (function () {
  10266. function FulFillmentAgregator() {
  10267. this.count = 0;
  10268. this.target = 0;
  10269. this.results = [];
  10270. }
  10271. return FulFillmentAgregator;
  10272. }());
  10273. var InternalPromise = /** @class */ (function () {
  10274. function InternalPromise(resolver) {
  10275. var _this = this;
  10276. this._state = PromiseStates.Pending;
  10277. this._children = new Array();
  10278. this._rejectWasConsumed = false;
  10279. if (!resolver) {
  10280. return;
  10281. }
  10282. try {
  10283. resolver(function (value) {
  10284. _this._resolve(value);
  10285. }, function (reason) {
  10286. _this._reject(reason);
  10287. });
  10288. }
  10289. catch (e) {
  10290. this._reject(e);
  10291. }
  10292. }
  10293. Object.defineProperty(InternalPromise.prototype, "_result", {
  10294. get: function () {
  10295. return this._resultValue;
  10296. },
  10297. set: function (value) {
  10298. this._resultValue = value;
  10299. if (this._parent && this._parent._result === undefined) {
  10300. this._parent._result = value;
  10301. }
  10302. },
  10303. enumerable: true,
  10304. configurable: true
  10305. });
  10306. InternalPromise.prototype.catch = function (onRejected) {
  10307. return this.then(undefined, onRejected);
  10308. };
  10309. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10310. var _this = this;
  10311. var newPromise = new InternalPromise();
  10312. newPromise._onFulfilled = onFulfilled;
  10313. newPromise._onRejected = onRejected;
  10314. // Composition
  10315. this._children.push(newPromise);
  10316. newPromise._parent = this;
  10317. if (this._state !== PromiseStates.Pending) {
  10318. BABYLON.Tools.SetImmediate(function () {
  10319. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10320. var returnedValue = newPromise._resolve(_this._result);
  10321. if (returnedValue !== undefined && returnedValue !== null) {
  10322. if (returnedValue._state !== undefined) {
  10323. var returnedPromise = returnedValue;
  10324. newPromise._children.push(returnedPromise);
  10325. returnedPromise._parent = newPromise;
  10326. newPromise = returnedPromise;
  10327. }
  10328. else {
  10329. newPromise._result = returnedValue;
  10330. }
  10331. }
  10332. }
  10333. else {
  10334. newPromise._reject(_this._reason);
  10335. }
  10336. });
  10337. }
  10338. return newPromise;
  10339. };
  10340. InternalPromise.prototype._moveChildren = function (children) {
  10341. var _this = this;
  10342. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10343. this._children.forEach(function (child) {
  10344. child._parent = _this;
  10345. });
  10346. if (this._state === PromiseStates.Fulfilled) {
  10347. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10348. var child = _b[_i];
  10349. child._resolve(this._result);
  10350. }
  10351. }
  10352. else if (this._state === PromiseStates.Rejected) {
  10353. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10354. var child = _d[_c];
  10355. child._reject(this._reason);
  10356. }
  10357. }
  10358. var _a;
  10359. };
  10360. InternalPromise.prototype._resolve = function (value) {
  10361. try {
  10362. this._state = PromiseStates.Fulfilled;
  10363. var returnedValue = null;
  10364. if (this._onFulfilled) {
  10365. returnedValue = this._onFulfilled(value);
  10366. }
  10367. if (returnedValue !== undefined && returnedValue !== null) {
  10368. if (returnedValue._state !== undefined) {
  10369. // Transmit children
  10370. var returnedPromise = returnedValue;
  10371. returnedPromise._parent = this;
  10372. returnedPromise._moveChildren(this._children);
  10373. value = returnedPromise._result;
  10374. }
  10375. else {
  10376. value = returnedValue;
  10377. }
  10378. }
  10379. this._result = value;
  10380. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10381. var child = _a[_i];
  10382. child._resolve(value);
  10383. }
  10384. this._children.length = 0;
  10385. delete this._onFulfilled;
  10386. delete this._onRejected;
  10387. }
  10388. catch (e) {
  10389. this._reject(e, true);
  10390. }
  10391. };
  10392. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10393. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10394. this._state = PromiseStates.Rejected;
  10395. this._reason = reason;
  10396. if (this._onRejected && !onLocalThrow) {
  10397. try {
  10398. this._onRejected(reason);
  10399. this._rejectWasConsumed = true;
  10400. }
  10401. catch (e) {
  10402. reason = e;
  10403. }
  10404. }
  10405. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10406. var child = _a[_i];
  10407. if (this._rejectWasConsumed) {
  10408. child._resolve(null);
  10409. }
  10410. else {
  10411. child._reject(reason);
  10412. }
  10413. }
  10414. this._children.length = 0;
  10415. delete this._onFulfilled;
  10416. delete this._onRejected;
  10417. };
  10418. InternalPromise.resolve = function (value) {
  10419. var newPromise = new InternalPromise();
  10420. newPromise._resolve(value);
  10421. return newPromise;
  10422. };
  10423. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10424. promise.then(function (value) {
  10425. agregator.results[index] = value;
  10426. agregator.count++;
  10427. if (agregator.count === agregator.target) {
  10428. agregator.rootPromise._resolve(agregator.results);
  10429. }
  10430. return null;
  10431. }, function (reason) {
  10432. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10433. agregator.rootPromise._reject(reason);
  10434. }
  10435. });
  10436. };
  10437. InternalPromise.all = function (promises) {
  10438. var newPromise = new InternalPromise();
  10439. var agregator = new FulFillmentAgregator();
  10440. agregator.target = promises.length;
  10441. agregator.rootPromise = newPromise;
  10442. if (promises.length) {
  10443. for (var index = 0; index < promises.length; index++) {
  10444. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10445. }
  10446. }
  10447. else {
  10448. newPromise._resolve([]);
  10449. }
  10450. return newPromise;
  10451. };
  10452. InternalPromise.race = function (promises) {
  10453. var newPromise = new InternalPromise();
  10454. if (promises.length) {
  10455. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10456. var promise = promises_1[_i];
  10457. promise.then(function (value) {
  10458. if (newPromise) {
  10459. newPromise._resolve(value);
  10460. newPromise = null;
  10461. }
  10462. return null;
  10463. }, function (reason) {
  10464. if (newPromise) {
  10465. newPromise._reject(reason);
  10466. newPromise = null;
  10467. }
  10468. });
  10469. }
  10470. }
  10471. return newPromise;
  10472. };
  10473. return InternalPromise;
  10474. }());
  10475. /**
  10476. * Helper class that provides a small promise polyfill
  10477. */
  10478. var PromisePolyfill = /** @class */ (function () {
  10479. function PromisePolyfill() {
  10480. }
  10481. /**
  10482. * Static function used to check if the polyfill is required
  10483. * If this is the case then the function will inject the polyfill to window.Promise
  10484. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10485. */
  10486. PromisePolyfill.Apply = function (force) {
  10487. if (force === void 0) { force = false; }
  10488. if (force || typeof Promise === 'undefined') {
  10489. var root = window;
  10490. root.Promise = InternalPromise;
  10491. }
  10492. };
  10493. return PromisePolyfill;
  10494. }());
  10495. BABYLON.PromisePolyfill = PromisePolyfill;
  10496. })(BABYLON || (BABYLON = {}));
  10497. //# sourceMappingURL=babylon.promise.js.map
  10498. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10499. var BABYLON;
  10500. (function (BABYLON) {
  10501. /**
  10502. * Helper class to push actions to a pool of workers.
  10503. */
  10504. var WorkerPool = /** @class */ (function () {
  10505. /**
  10506. * Constructor
  10507. * @param workers Array of workers to use for actions
  10508. */
  10509. function WorkerPool(workers) {
  10510. this._pendingActions = new Array();
  10511. this._workerInfos = workers.map(function (worker) { return ({
  10512. worker: worker,
  10513. active: false
  10514. }); });
  10515. }
  10516. /**
  10517. * Terminates all workers and clears any pending actions.
  10518. */
  10519. WorkerPool.prototype.dispose = function () {
  10520. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10521. var workerInfo = _a[_i];
  10522. workerInfo.worker.terminate();
  10523. }
  10524. delete this._workerInfos;
  10525. delete this._pendingActions;
  10526. };
  10527. /**
  10528. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10529. * pended until a worker has completed its action.
  10530. * @param action The action to perform. Call onComplete when the action is complete.
  10531. */
  10532. WorkerPool.prototype.push = function (action) {
  10533. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10534. var workerInfo = _a[_i];
  10535. if (!workerInfo.active) {
  10536. this._execute(workerInfo, action);
  10537. return;
  10538. }
  10539. }
  10540. this._pendingActions.push(action);
  10541. };
  10542. WorkerPool.prototype._execute = function (workerInfo, action) {
  10543. var _this = this;
  10544. workerInfo.active = true;
  10545. action(workerInfo.worker, function () {
  10546. workerInfo.active = false;
  10547. var nextAction = _this._pendingActions.shift();
  10548. if (nextAction) {
  10549. _this._execute(workerInfo, nextAction);
  10550. }
  10551. });
  10552. };
  10553. return WorkerPool;
  10554. }());
  10555. BABYLON.WorkerPool = WorkerPool;
  10556. })(BABYLON || (BABYLON = {}));
  10557. //# sourceMappingURL=babylon.workerPool.js.map
  10558. var BABYLON;
  10559. (function (BABYLON) {
  10560. /**
  10561. * @hidden
  10562. **/
  10563. var _AlphaState = /** @class */ (function () {
  10564. /**
  10565. * Initializes the state.
  10566. */
  10567. function _AlphaState() {
  10568. this._isAlphaBlendDirty = false;
  10569. this._isBlendFunctionParametersDirty = false;
  10570. this._isBlendEquationParametersDirty = false;
  10571. this._isBlendConstantsDirty = false;
  10572. this._alphaBlend = false;
  10573. this._blendFunctionParameters = new Array(4);
  10574. this._blendEquationParameters = new Array(2);
  10575. this._blendConstants = new Array(4);
  10576. this.reset();
  10577. }
  10578. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10579. get: function () {
  10580. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10581. },
  10582. enumerable: true,
  10583. configurable: true
  10584. });
  10585. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10586. get: function () {
  10587. return this._alphaBlend;
  10588. },
  10589. set: function (value) {
  10590. if (this._alphaBlend === value) {
  10591. return;
  10592. }
  10593. this._alphaBlend = value;
  10594. this._isAlphaBlendDirty = true;
  10595. },
  10596. enumerable: true,
  10597. configurable: true
  10598. });
  10599. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10600. if (this._blendConstants[0] === r &&
  10601. this._blendConstants[1] === g &&
  10602. this._blendConstants[2] === b &&
  10603. this._blendConstants[3] === a) {
  10604. return;
  10605. }
  10606. this._blendConstants[0] = r;
  10607. this._blendConstants[1] = g;
  10608. this._blendConstants[2] = b;
  10609. this._blendConstants[3] = a;
  10610. this._isBlendConstantsDirty = true;
  10611. };
  10612. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10613. if (this._blendFunctionParameters[0] === value0 &&
  10614. this._blendFunctionParameters[1] === value1 &&
  10615. this._blendFunctionParameters[2] === value2 &&
  10616. this._blendFunctionParameters[3] === value3) {
  10617. return;
  10618. }
  10619. this._blendFunctionParameters[0] = value0;
  10620. this._blendFunctionParameters[1] = value1;
  10621. this._blendFunctionParameters[2] = value2;
  10622. this._blendFunctionParameters[3] = value3;
  10623. this._isBlendFunctionParametersDirty = true;
  10624. };
  10625. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10626. if (this._blendEquationParameters[0] === rgb &&
  10627. this._blendEquationParameters[1] === alpha) {
  10628. return;
  10629. }
  10630. this._blendEquationParameters[0] = rgb;
  10631. this._blendEquationParameters[1] = alpha;
  10632. this._isBlendEquationParametersDirty = true;
  10633. };
  10634. _AlphaState.prototype.reset = function () {
  10635. this._alphaBlend = false;
  10636. this._blendFunctionParameters[0] = null;
  10637. this._blendFunctionParameters[1] = null;
  10638. this._blendFunctionParameters[2] = null;
  10639. this._blendFunctionParameters[3] = null;
  10640. this._blendEquationParameters[0] = null;
  10641. this._blendEquationParameters[1] = null;
  10642. this._blendConstants[0] = null;
  10643. this._blendConstants[1] = null;
  10644. this._blendConstants[2] = null;
  10645. this._blendConstants[3] = null;
  10646. this._isAlphaBlendDirty = true;
  10647. this._isBlendFunctionParametersDirty = false;
  10648. this._isBlendEquationParametersDirty = false;
  10649. this._isBlendConstantsDirty = false;
  10650. };
  10651. _AlphaState.prototype.apply = function (gl) {
  10652. if (!this.isDirty) {
  10653. return;
  10654. }
  10655. // Alpha blend
  10656. if (this._isAlphaBlendDirty) {
  10657. if (this._alphaBlend) {
  10658. gl.enable(gl.BLEND);
  10659. }
  10660. else {
  10661. gl.disable(gl.BLEND);
  10662. }
  10663. this._isAlphaBlendDirty = false;
  10664. }
  10665. // Alpha function
  10666. if (this._isBlendFunctionParametersDirty) {
  10667. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10668. this._isBlendFunctionParametersDirty = false;
  10669. }
  10670. // Alpha equation
  10671. if (this._isBlendEquationParametersDirty) {
  10672. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10673. this._isBlendEquationParametersDirty = false;
  10674. }
  10675. // Constants
  10676. if (this._isBlendConstantsDirty) {
  10677. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10678. this._isBlendConstantsDirty = false;
  10679. }
  10680. };
  10681. return _AlphaState;
  10682. }());
  10683. BABYLON._AlphaState = _AlphaState;
  10684. })(BABYLON || (BABYLON = {}));
  10685. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10686. var BABYLON;
  10687. (function (BABYLON) {
  10688. /**
  10689. * @hidden
  10690. **/
  10691. var _DepthCullingState = /** @class */ (function () {
  10692. /**
  10693. * Initializes the state.
  10694. */
  10695. function _DepthCullingState() {
  10696. this._isDepthTestDirty = false;
  10697. this._isDepthMaskDirty = false;
  10698. this._isDepthFuncDirty = false;
  10699. this._isCullFaceDirty = false;
  10700. this._isCullDirty = false;
  10701. this._isZOffsetDirty = false;
  10702. this._isFrontFaceDirty = false;
  10703. this.reset();
  10704. }
  10705. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10706. get: function () {
  10707. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10708. },
  10709. enumerable: true,
  10710. configurable: true
  10711. });
  10712. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10713. get: function () {
  10714. return this._zOffset;
  10715. },
  10716. set: function (value) {
  10717. if (this._zOffset === value) {
  10718. return;
  10719. }
  10720. this._zOffset = value;
  10721. this._isZOffsetDirty = true;
  10722. },
  10723. enumerable: true,
  10724. configurable: true
  10725. });
  10726. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10727. get: function () {
  10728. return this._cullFace;
  10729. },
  10730. set: function (value) {
  10731. if (this._cullFace === value) {
  10732. return;
  10733. }
  10734. this._cullFace = value;
  10735. this._isCullFaceDirty = true;
  10736. },
  10737. enumerable: true,
  10738. configurable: true
  10739. });
  10740. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10741. get: function () {
  10742. return this._cull;
  10743. },
  10744. set: function (value) {
  10745. if (this._cull === value) {
  10746. return;
  10747. }
  10748. this._cull = value;
  10749. this._isCullDirty = true;
  10750. },
  10751. enumerable: true,
  10752. configurable: true
  10753. });
  10754. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10755. get: function () {
  10756. return this._depthFunc;
  10757. },
  10758. set: function (value) {
  10759. if (this._depthFunc === value) {
  10760. return;
  10761. }
  10762. this._depthFunc = value;
  10763. this._isDepthFuncDirty = true;
  10764. },
  10765. enumerable: true,
  10766. configurable: true
  10767. });
  10768. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10769. get: function () {
  10770. return this._depthMask;
  10771. },
  10772. set: function (value) {
  10773. if (this._depthMask === value) {
  10774. return;
  10775. }
  10776. this._depthMask = value;
  10777. this._isDepthMaskDirty = true;
  10778. },
  10779. enumerable: true,
  10780. configurable: true
  10781. });
  10782. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10783. get: function () {
  10784. return this._depthTest;
  10785. },
  10786. set: function (value) {
  10787. if (this._depthTest === value) {
  10788. return;
  10789. }
  10790. this._depthTest = value;
  10791. this._isDepthTestDirty = true;
  10792. },
  10793. enumerable: true,
  10794. configurable: true
  10795. });
  10796. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10797. get: function () {
  10798. return this._frontFace;
  10799. },
  10800. set: function (value) {
  10801. if (this._frontFace === value) {
  10802. return;
  10803. }
  10804. this._frontFace = value;
  10805. this._isFrontFaceDirty = true;
  10806. },
  10807. enumerable: true,
  10808. configurable: true
  10809. });
  10810. _DepthCullingState.prototype.reset = function () {
  10811. this._depthMask = true;
  10812. this._depthTest = true;
  10813. this._depthFunc = null;
  10814. this._cullFace = null;
  10815. this._cull = null;
  10816. this._zOffset = 0;
  10817. this._frontFace = null;
  10818. this._isDepthTestDirty = true;
  10819. this._isDepthMaskDirty = true;
  10820. this._isDepthFuncDirty = false;
  10821. this._isCullFaceDirty = false;
  10822. this._isCullDirty = false;
  10823. this._isZOffsetDirty = false;
  10824. this._isFrontFaceDirty = false;
  10825. };
  10826. _DepthCullingState.prototype.apply = function (gl) {
  10827. if (!this.isDirty) {
  10828. return;
  10829. }
  10830. // Cull
  10831. if (this._isCullDirty) {
  10832. if (this.cull) {
  10833. gl.enable(gl.CULL_FACE);
  10834. }
  10835. else {
  10836. gl.disable(gl.CULL_FACE);
  10837. }
  10838. this._isCullDirty = false;
  10839. }
  10840. // Cull face
  10841. if (this._isCullFaceDirty) {
  10842. gl.cullFace(this.cullFace);
  10843. this._isCullFaceDirty = false;
  10844. }
  10845. // Depth mask
  10846. if (this._isDepthMaskDirty) {
  10847. gl.depthMask(this.depthMask);
  10848. this._isDepthMaskDirty = false;
  10849. }
  10850. // Depth test
  10851. if (this._isDepthTestDirty) {
  10852. if (this.depthTest) {
  10853. gl.enable(gl.DEPTH_TEST);
  10854. }
  10855. else {
  10856. gl.disable(gl.DEPTH_TEST);
  10857. }
  10858. this._isDepthTestDirty = false;
  10859. }
  10860. // Depth func
  10861. if (this._isDepthFuncDirty) {
  10862. gl.depthFunc(this.depthFunc);
  10863. this._isDepthFuncDirty = false;
  10864. }
  10865. // zOffset
  10866. if (this._isZOffsetDirty) {
  10867. if (this.zOffset) {
  10868. gl.enable(gl.POLYGON_OFFSET_FILL);
  10869. gl.polygonOffset(this.zOffset, 0);
  10870. }
  10871. else {
  10872. gl.disable(gl.POLYGON_OFFSET_FILL);
  10873. }
  10874. this._isZOffsetDirty = false;
  10875. }
  10876. // Front face
  10877. if (this._isFrontFaceDirty) {
  10878. gl.frontFace(this.frontFace);
  10879. this._isFrontFaceDirty = false;
  10880. }
  10881. };
  10882. return _DepthCullingState;
  10883. }());
  10884. BABYLON._DepthCullingState = _DepthCullingState;
  10885. })(BABYLON || (BABYLON = {}));
  10886. //# sourceMappingURL=babylon.depthCullingState.js.map
  10887. var BABYLON;
  10888. (function (BABYLON) {
  10889. /**
  10890. * @hidden
  10891. **/
  10892. var _StencilState = /** @class */ (function () {
  10893. function _StencilState() {
  10894. this._isStencilTestDirty = false;
  10895. this._isStencilMaskDirty = false;
  10896. this._isStencilFuncDirty = false;
  10897. this._isStencilOpDirty = false;
  10898. this.reset();
  10899. }
  10900. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10901. get: function () {
  10902. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10903. },
  10904. enumerable: true,
  10905. configurable: true
  10906. });
  10907. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10908. get: function () {
  10909. return this._stencilFunc;
  10910. },
  10911. set: function (value) {
  10912. if (this._stencilFunc === value) {
  10913. return;
  10914. }
  10915. this._stencilFunc = value;
  10916. this._isStencilFuncDirty = true;
  10917. },
  10918. enumerable: true,
  10919. configurable: true
  10920. });
  10921. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10922. get: function () {
  10923. return this._stencilFuncRef;
  10924. },
  10925. set: function (value) {
  10926. if (this._stencilFuncRef === value) {
  10927. return;
  10928. }
  10929. this._stencilFuncRef = value;
  10930. this._isStencilFuncDirty = true;
  10931. },
  10932. enumerable: true,
  10933. configurable: true
  10934. });
  10935. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10936. get: function () {
  10937. return this._stencilFuncMask;
  10938. },
  10939. set: function (value) {
  10940. if (this._stencilFuncMask === value) {
  10941. return;
  10942. }
  10943. this._stencilFuncMask = value;
  10944. this._isStencilFuncDirty = true;
  10945. },
  10946. enumerable: true,
  10947. configurable: true
  10948. });
  10949. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10950. get: function () {
  10951. return this._stencilOpStencilFail;
  10952. },
  10953. set: function (value) {
  10954. if (this._stencilOpStencilFail === value) {
  10955. return;
  10956. }
  10957. this._stencilOpStencilFail = value;
  10958. this._isStencilOpDirty = true;
  10959. },
  10960. enumerable: true,
  10961. configurable: true
  10962. });
  10963. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10964. get: function () {
  10965. return this._stencilOpDepthFail;
  10966. },
  10967. set: function (value) {
  10968. if (this._stencilOpDepthFail === value) {
  10969. return;
  10970. }
  10971. this._stencilOpDepthFail = value;
  10972. this._isStencilOpDirty = true;
  10973. },
  10974. enumerable: true,
  10975. configurable: true
  10976. });
  10977. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10978. get: function () {
  10979. return this._stencilOpStencilDepthPass;
  10980. },
  10981. set: function (value) {
  10982. if (this._stencilOpStencilDepthPass === value) {
  10983. return;
  10984. }
  10985. this._stencilOpStencilDepthPass = value;
  10986. this._isStencilOpDirty = true;
  10987. },
  10988. enumerable: true,
  10989. configurable: true
  10990. });
  10991. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10992. get: function () {
  10993. return this._stencilMask;
  10994. },
  10995. set: function (value) {
  10996. if (this._stencilMask === value) {
  10997. return;
  10998. }
  10999. this._stencilMask = value;
  11000. this._isStencilMaskDirty = true;
  11001. },
  11002. enumerable: true,
  11003. configurable: true
  11004. });
  11005. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11006. get: function () {
  11007. return this._stencilTest;
  11008. },
  11009. set: function (value) {
  11010. if (this._stencilTest === value) {
  11011. return;
  11012. }
  11013. this._stencilTest = value;
  11014. this._isStencilTestDirty = true;
  11015. },
  11016. enumerable: true,
  11017. configurable: true
  11018. });
  11019. _StencilState.prototype.reset = function () {
  11020. this._stencilTest = false;
  11021. this._stencilMask = 0xFF;
  11022. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11023. this._stencilFuncRef = 1;
  11024. this._stencilFuncMask = 0xFF;
  11025. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11026. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11027. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11028. this._isStencilTestDirty = true;
  11029. this._isStencilMaskDirty = true;
  11030. this._isStencilFuncDirty = true;
  11031. this._isStencilOpDirty = true;
  11032. };
  11033. _StencilState.prototype.apply = function (gl) {
  11034. if (!this.isDirty) {
  11035. return;
  11036. }
  11037. // Stencil test
  11038. if (this._isStencilTestDirty) {
  11039. if (this.stencilTest) {
  11040. gl.enable(gl.STENCIL_TEST);
  11041. }
  11042. else {
  11043. gl.disable(gl.STENCIL_TEST);
  11044. }
  11045. this._isStencilTestDirty = false;
  11046. }
  11047. // Stencil mask
  11048. if (this._isStencilMaskDirty) {
  11049. gl.stencilMask(this.stencilMask);
  11050. this._isStencilMaskDirty = false;
  11051. }
  11052. // Stencil func
  11053. if (this._isStencilFuncDirty) {
  11054. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11055. this._isStencilFuncDirty = false;
  11056. }
  11057. // Stencil op
  11058. if (this._isStencilOpDirty) {
  11059. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11060. this._isStencilOpDirty = false;
  11061. }
  11062. };
  11063. return _StencilState;
  11064. }());
  11065. BABYLON._StencilState = _StencilState;
  11066. })(BABYLON || (BABYLON = {}));
  11067. //# sourceMappingURL=babylon.stencilState.js.map
  11068. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11069. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11070. s = arguments[i];
  11071. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11072. t[p] = s[p];
  11073. }
  11074. return t;
  11075. };
  11076. var BABYLON;
  11077. (function (BABYLON) {
  11078. /**
  11079. * Keeps track of all the buffer info used in engine.
  11080. */
  11081. var BufferPointer = /** @class */ (function () {
  11082. function BufferPointer() {
  11083. }
  11084. return BufferPointer;
  11085. }());
  11086. /**
  11087. * Interface for attribute information associated with buffer instanciation
  11088. */
  11089. var InstancingAttributeInfo = /** @class */ (function () {
  11090. function InstancingAttributeInfo() {
  11091. }
  11092. return InstancingAttributeInfo;
  11093. }());
  11094. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11095. /**
  11096. * Define options used to create a render target texture
  11097. */
  11098. var RenderTargetCreationOptions = /** @class */ (function () {
  11099. function RenderTargetCreationOptions() {
  11100. }
  11101. return RenderTargetCreationOptions;
  11102. }());
  11103. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11104. /**
  11105. * Define options used to create a depth texture
  11106. */
  11107. var DepthTextureCreationOptions = /** @class */ (function () {
  11108. function DepthTextureCreationOptions() {
  11109. }
  11110. return DepthTextureCreationOptions;
  11111. }());
  11112. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11113. /**
  11114. * Class used to describe the capabilities of the engine relatively to the current browser
  11115. */
  11116. var EngineCapabilities = /** @class */ (function () {
  11117. function EngineCapabilities() {
  11118. }
  11119. return EngineCapabilities;
  11120. }());
  11121. BABYLON.EngineCapabilities = EngineCapabilities;
  11122. /**
  11123. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11124. */
  11125. var Engine = /** @class */ (function () {
  11126. /**
  11127. * Creates a new engine
  11128. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11129. * @param antialias defines enable antialiasing (default: false)
  11130. * @param options defines further options to be sent to the getContext() function
  11131. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11132. */
  11133. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11134. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11135. var _this = this;
  11136. // Public members
  11137. /**
  11138. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11139. */
  11140. this.forcePOTTextures = false;
  11141. /**
  11142. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11143. */
  11144. this.isFullscreen = false;
  11145. /**
  11146. * Gets a boolean indicating if the pointer is currently locked
  11147. */
  11148. this.isPointerLock = false;
  11149. /**
  11150. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11151. */
  11152. this.cullBackFaces = true;
  11153. /**
  11154. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11155. */
  11156. this.renderEvenInBackground = true;
  11157. /**
  11158. * Gets or sets a boolean indicating that cache can be kept between frames
  11159. */
  11160. this.preventCacheWipeBetweenFrames = false;
  11161. /**
  11162. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11163. **/
  11164. this.enableOfflineSupport = false;
  11165. /**
  11166. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11167. **/
  11168. this.disableManifestCheck = false;
  11169. /**
  11170. * Gets the list of created scenes
  11171. */
  11172. this.scenes = new Array();
  11173. /**
  11174. * Gets the list of created postprocesses
  11175. */
  11176. this.postProcesses = new Array();
  11177. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11178. this.validateShaderPrograms = false;
  11179. // Observables
  11180. /**
  11181. * Observable event triggered each time the rendering canvas is resized
  11182. */
  11183. this.onResizeObservable = new BABYLON.Observable();
  11184. /**
  11185. * Observable event triggered each time the canvas loses focus
  11186. */
  11187. this.onCanvasBlurObservable = new BABYLON.Observable();
  11188. /**
  11189. * Observable event triggered each time the canvas gains focus
  11190. */
  11191. this.onCanvasFocusObservable = new BABYLON.Observable();
  11192. /**
  11193. * Observable event triggered each time the canvas receives pointerout event
  11194. */
  11195. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11196. /**
  11197. * Observable event triggered before each texture is initialized
  11198. */
  11199. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11200. //WebVR
  11201. this._vrDisplay = undefined;
  11202. this._vrSupported = false;
  11203. this._vrExclusivePointerMode = false;
  11204. // Uniform buffers list
  11205. /**
  11206. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11207. */
  11208. this.disableUniformBuffers = false;
  11209. /** @hidden */
  11210. this._uniformBuffers = new Array();
  11211. // Observables
  11212. /**
  11213. * Observable raised when the engine begins a new frame
  11214. */
  11215. this.onBeginFrameObservable = new BABYLON.Observable();
  11216. /**
  11217. * Observable raised when the engine ends the current frame
  11218. */
  11219. this.onEndFrameObservable = new BABYLON.Observable();
  11220. /**
  11221. * Observable raised when the engine is about to compile a shader
  11222. */
  11223. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11224. /**
  11225. * Observable raised when the engine has jsut compiled a shader
  11226. */
  11227. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11228. this._windowIsBackground = false;
  11229. this._webGLVersion = 1.0;
  11230. /** @hidden */
  11231. this._badOS = false;
  11232. /** @hidden */
  11233. this._badDesktopOS = false;
  11234. /**
  11235. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11236. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11237. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11238. */
  11239. this.disableTextureBindingOptimization = false;
  11240. /**
  11241. * Observable signaled when VR display mode changes
  11242. */
  11243. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11244. /**
  11245. * Observable signaled when VR request present is complete
  11246. */
  11247. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11248. /**
  11249. * Observable signaled when VR request present starts
  11250. */
  11251. this.onVRRequestPresentStart = new BABYLON.Observable();
  11252. this._colorWrite = true;
  11253. /** @hidden */
  11254. this._drawCalls = new BABYLON.PerfCounter();
  11255. /** @hidden */
  11256. this._textureCollisions = new BABYLON.PerfCounter();
  11257. this._renderingQueueLaunched = false;
  11258. this._activeRenderLoops = new Array();
  11259. // Deterministic lockstepMaxSteps
  11260. this._deterministicLockstep = false;
  11261. this._lockstepMaxSteps = 4;
  11262. // Lost context
  11263. /**
  11264. * Observable signaled when a context lost event is raised
  11265. */
  11266. this.onContextLostObservable = new BABYLON.Observable();
  11267. /**
  11268. * Observable signaled when a context restored event is raised
  11269. */
  11270. this.onContextRestoredObservable = new BABYLON.Observable();
  11271. this._contextWasLost = false;
  11272. this._doNotHandleContextLost = false;
  11273. // FPS
  11274. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11275. this._fps = 60;
  11276. this._deltaTime = 0;
  11277. /**
  11278. * Turn this value on if you want to pause FPS computation when in background
  11279. */
  11280. this.disablePerformanceMonitorInBackground = false;
  11281. // States
  11282. /** @hidden */
  11283. this._depthCullingState = new BABYLON._DepthCullingState();
  11284. /** @hidden */
  11285. this._stencilState = new BABYLON._StencilState();
  11286. /** @hidden */
  11287. this._alphaState = new BABYLON._AlphaState();
  11288. /** @hidden */
  11289. this._alphaMode = Engine.ALPHA_DISABLE;
  11290. // Cache
  11291. this._internalTexturesCache = new Array();
  11292. /** @hidden */
  11293. this._activeChannel = 0;
  11294. this._currentTextureChannel = -1;
  11295. /** @hidden */
  11296. this._boundTexturesCache = {};
  11297. this._compiledEffects = {};
  11298. this._vertexAttribArraysEnabled = [];
  11299. this._uintIndicesCurrentlySet = false;
  11300. this._currentBoundBuffer = new Array();
  11301. /** @hidden */
  11302. this._currentFramebuffer = null;
  11303. this._currentBufferPointers = new Array();
  11304. this._currentInstanceLocations = new Array();
  11305. this._currentInstanceBuffers = new Array();
  11306. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11307. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11308. this._vaoRecordInProgress = false;
  11309. this._mustWipeVertexAttributes = false;
  11310. this._nextFreeTextureSlots = new Array();
  11311. this._maxSimultaneousTextures = 0;
  11312. this._activeRequests = new Array();
  11313. // Hardware supported Compressed Textures
  11314. this._texturesSupported = new Array();
  11315. /**
  11316. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11317. */
  11318. this.premultipliedAlpha = true;
  11319. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11320. this._onVRFullScreenTriggered = function () {
  11321. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11322. //get the old size before we change
  11323. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11324. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11325. //get the width and height, change the render size
  11326. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11327. _this.setHardwareScalingLevel(1);
  11328. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11329. }
  11330. else {
  11331. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11332. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11333. }
  11334. };
  11335. this._unpackFlipYCached = null;
  11336. this._boundUniforms = {};
  11337. // Register promises
  11338. BABYLON.PromisePolyfill.Apply();
  11339. var canvas = null;
  11340. Engine.Instances.push(this);
  11341. if (!canvasOrContext) {
  11342. return;
  11343. }
  11344. options = options || {};
  11345. if (canvasOrContext.getContext) {
  11346. canvas = canvasOrContext;
  11347. this._renderingCanvas = canvas;
  11348. if (antialias != null) {
  11349. options.antialias = antialias;
  11350. }
  11351. if (options.deterministicLockstep === undefined) {
  11352. options.deterministicLockstep = false;
  11353. }
  11354. if (options.lockstepMaxSteps === undefined) {
  11355. options.lockstepMaxSteps = 4;
  11356. }
  11357. if (options.preserveDrawingBuffer === undefined) {
  11358. options.preserveDrawingBuffer = false;
  11359. }
  11360. if (options.audioEngine === undefined) {
  11361. options.audioEngine = true;
  11362. }
  11363. if (options.stencil === undefined) {
  11364. options.stencil = true;
  11365. }
  11366. if (options.premultipliedAlpha === false) {
  11367. this.premultipliedAlpha = false;
  11368. }
  11369. this._deterministicLockstep = options.deterministicLockstep;
  11370. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11371. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11372. // Exceptions
  11373. if (navigator && navigator.userAgent) {
  11374. var ua = navigator.userAgent;
  11375. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11376. var exception = _a[_i];
  11377. var key = exception.key;
  11378. var targets = exception.targets;
  11379. if (ua.indexOf(key) > -1) {
  11380. if (exception.capture && exception.captureConstraint) {
  11381. var capture = exception.capture;
  11382. var constraint = exception.captureConstraint;
  11383. var regex = new RegExp(capture);
  11384. var matches = regex.exec(ua);
  11385. if (matches && matches.length > 0) {
  11386. var capturedValue = parseInt(matches[matches.length - 1]);
  11387. if (capturedValue >= constraint) {
  11388. continue;
  11389. }
  11390. }
  11391. }
  11392. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11393. var target = targets_1[_b];
  11394. switch (target) {
  11395. case "uniformBuffer":
  11396. this.disableUniformBuffers = true;
  11397. break;
  11398. case "textureBindingOptimization":
  11399. this.disableTextureBindingOptimization = true;
  11400. break;
  11401. }
  11402. }
  11403. }
  11404. }
  11405. }
  11406. // GL
  11407. if (!options.disableWebGL2Support) {
  11408. try {
  11409. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11410. if (this._gl) {
  11411. this._webGLVersion = 2.0;
  11412. }
  11413. }
  11414. catch (e) {
  11415. // Do nothing
  11416. }
  11417. }
  11418. if (!this._gl) {
  11419. if (!canvas) {
  11420. throw new Error("The provided canvas is null or undefined.");
  11421. }
  11422. try {
  11423. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11424. }
  11425. catch (e) {
  11426. throw new Error("WebGL not supported");
  11427. }
  11428. }
  11429. if (!this._gl) {
  11430. throw new Error("WebGL not supported");
  11431. }
  11432. this._onCanvasFocus = function () {
  11433. _this.onCanvasFocusObservable.notifyObservers(_this);
  11434. };
  11435. this._onCanvasBlur = function () {
  11436. _this.onCanvasBlurObservable.notifyObservers(_this);
  11437. };
  11438. canvas.addEventListener("focus", this._onCanvasFocus);
  11439. canvas.addEventListener("blur", this._onCanvasBlur);
  11440. this._onBlur = function () {
  11441. if (_this.disablePerformanceMonitorInBackground) {
  11442. _this._performanceMonitor.disable();
  11443. }
  11444. _this._windowIsBackground = true;
  11445. };
  11446. this._onFocus = function () {
  11447. if (_this.disablePerformanceMonitorInBackground) {
  11448. _this._performanceMonitor.enable();
  11449. }
  11450. _this._windowIsBackground = false;
  11451. };
  11452. this._onCanvasPointerOut = function (ev) {
  11453. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11454. };
  11455. window.addEventListener("blur", this._onBlur);
  11456. window.addEventListener("focus", this._onFocus);
  11457. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11458. // Context lost
  11459. if (!this._doNotHandleContextLost) {
  11460. this._onContextLost = function (evt) {
  11461. evt.preventDefault();
  11462. _this._contextWasLost = true;
  11463. BABYLON.Tools.Warn("WebGL context lost.");
  11464. _this.onContextLostObservable.notifyObservers(_this);
  11465. };
  11466. this._onContextRestored = function (evt) {
  11467. // Adding a timeout to avoid race condition at browser level
  11468. setTimeout(function () {
  11469. // Rebuild gl context
  11470. _this._initGLContext();
  11471. // Rebuild effects
  11472. _this._rebuildEffects();
  11473. // Rebuild textures
  11474. _this._rebuildInternalTextures();
  11475. // Rebuild buffers
  11476. _this._rebuildBuffers();
  11477. // Cache
  11478. _this.wipeCaches(true);
  11479. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11480. _this.onContextRestoredObservable.notifyObservers(_this);
  11481. _this._contextWasLost = false;
  11482. }, 0);
  11483. };
  11484. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11485. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11486. }
  11487. }
  11488. else {
  11489. this._gl = canvasOrContext;
  11490. this._renderingCanvas = this._gl.canvas;
  11491. if (this._gl.renderbufferStorageMultisample) {
  11492. this._webGLVersion = 2.0;
  11493. }
  11494. options.stencil = this._gl.getContextAttributes().stencil;
  11495. }
  11496. // Viewport
  11497. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11498. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11499. this.resize();
  11500. this._isStencilEnable = options.stencil ? true : false;
  11501. this._initGLContext();
  11502. if (canvas) {
  11503. // Fullscreen
  11504. this._onFullscreenChange = function () {
  11505. if (document.fullscreen !== undefined) {
  11506. _this.isFullscreen = document.fullscreen;
  11507. }
  11508. else if (document.mozFullScreen !== undefined) {
  11509. _this.isFullscreen = document.mozFullScreen;
  11510. }
  11511. else if (document.webkitIsFullScreen !== undefined) {
  11512. _this.isFullscreen = document.webkitIsFullScreen;
  11513. }
  11514. else if (document.msIsFullScreen !== undefined) {
  11515. _this.isFullscreen = document.msIsFullScreen;
  11516. }
  11517. // Pointer lock
  11518. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11519. canvas.requestPointerLock = canvas.requestPointerLock ||
  11520. canvas.msRequestPointerLock ||
  11521. canvas.mozRequestPointerLock ||
  11522. canvas.webkitRequestPointerLock;
  11523. if (canvas.requestPointerLock) {
  11524. canvas.requestPointerLock();
  11525. }
  11526. }
  11527. };
  11528. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11529. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11530. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11531. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11532. // Pointer lock
  11533. this._onPointerLockChange = function () {
  11534. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11535. document.webkitPointerLockElement === canvas ||
  11536. document.msPointerLockElement === canvas ||
  11537. document.pointerLockElement === canvas);
  11538. };
  11539. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11540. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11541. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11542. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11543. this._onVRDisplayPointerRestricted = function () {
  11544. if (canvas) {
  11545. canvas.requestPointerLock();
  11546. }
  11547. };
  11548. this._onVRDisplayPointerUnrestricted = function () {
  11549. document.exitPointerLock();
  11550. };
  11551. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11552. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11553. }
  11554. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11555. Engine.audioEngine = new BABYLON.AudioEngine();
  11556. }
  11557. // Prepare buffer pointers
  11558. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11559. this._currentBufferPointers[i] = new BufferPointer();
  11560. }
  11561. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11562. // Load WebVR Devices
  11563. if (options.autoEnableWebVR) {
  11564. this.initWebVR();
  11565. }
  11566. // Detect if we are running on a faulty buggy OS.
  11567. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11568. // Detect if we are running on a faulty buggy desktop OS.
  11569. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11570. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11571. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11572. }
  11573. Object.defineProperty(Engine, "LastCreatedEngine", {
  11574. /**
  11575. * Gets the latest created engine
  11576. */
  11577. get: function () {
  11578. if (Engine.Instances.length === 0) {
  11579. return null;
  11580. }
  11581. return Engine.Instances[Engine.Instances.length - 1];
  11582. },
  11583. enumerable: true,
  11584. configurable: true
  11585. });
  11586. Object.defineProperty(Engine, "LastCreatedScene", {
  11587. /**
  11588. * Gets the latest created scene
  11589. */
  11590. get: function () {
  11591. var lastCreatedEngine = Engine.LastCreatedEngine;
  11592. if (!lastCreatedEngine) {
  11593. return null;
  11594. }
  11595. if (lastCreatedEngine.scenes.length === 0) {
  11596. return null;
  11597. }
  11598. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11599. },
  11600. enumerable: true,
  11601. configurable: true
  11602. });
  11603. /**
  11604. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11605. * @param flag defines which part of the materials must be marked as dirty
  11606. * @param predicate defines a predicate used to filter which materials should be affected
  11607. */
  11608. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11609. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11610. var engine = Engine.Instances[engineIndex];
  11611. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11612. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11613. }
  11614. }
  11615. };
  11616. Object.defineProperty(Engine, "Version", {
  11617. /**
  11618. * Returns the current version of the framework
  11619. */
  11620. get: function () {
  11621. return "3.3.0-alpha.11";
  11622. },
  11623. enumerable: true,
  11624. configurable: true
  11625. });
  11626. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11627. /**
  11628. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11629. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11630. */
  11631. get: function () {
  11632. return this._vrExclusivePointerMode;
  11633. },
  11634. enumerable: true,
  11635. configurable: true
  11636. });
  11637. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11638. /**
  11639. * Gets a boolean indicating that the engine supports uniform buffers
  11640. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11641. */
  11642. get: function () {
  11643. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11644. },
  11645. enumerable: true,
  11646. configurable: true
  11647. });
  11648. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11649. /**
  11650. * Gets a boolean indicating that only power of 2 textures are supported
  11651. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11652. */
  11653. get: function () {
  11654. return this._webGLVersion < 2 || this.forcePOTTextures;
  11655. },
  11656. enumerable: true,
  11657. configurable: true
  11658. });
  11659. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11660. /**
  11661. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11662. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11663. */
  11664. get: function () {
  11665. return this._doNotHandleContextLost;
  11666. },
  11667. set: function (value) {
  11668. this._doNotHandleContextLost = value;
  11669. },
  11670. enumerable: true,
  11671. configurable: true
  11672. });
  11673. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11674. /**
  11675. * Gets the performance monitor attached to this engine
  11676. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11677. */
  11678. get: function () {
  11679. return this._performanceMonitor;
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11685. /**
  11686. * Gets the list of texture formats supported
  11687. */
  11688. get: function () {
  11689. return this._texturesSupported;
  11690. },
  11691. enumerable: true,
  11692. configurable: true
  11693. });
  11694. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11695. /**
  11696. * Gets the list of texture formats in use
  11697. */
  11698. get: function () {
  11699. return this._textureFormatInUse;
  11700. },
  11701. enumerable: true,
  11702. configurable: true
  11703. });
  11704. Object.defineProperty(Engine.prototype, "currentViewport", {
  11705. /**
  11706. * Gets the current viewport
  11707. */
  11708. get: function () {
  11709. return this._cachedViewport;
  11710. },
  11711. enumerable: true,
  11712. configurable: true
  11713. });
  11714. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11715. /**
  11716. * Gets the default empty texture
  11717. */
  11718. get: function () {
  11719. if (!this._emptyTexture) {
  11720. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11721. }
  11722. return this._emptyTexture;
  11723. },
  11724. enumerable: true,
  11725. configurable: true
  11726. });
  11727. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11728. /**
  11729. * Gets the default empty 3D texture
  11730. */
  11731. get: function () {
  11732. if (!this._emptyTexture3D) {
  11733. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11734. }
  11735. return this._emptyTexture3D;
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11741. /**
  11742. * Gets the default empty cube texture
  11743. */
  11744. get: function () {
  11745. if (!this._emptyCubeTexture) {
  11746. var faceData = new Uint8Array(4);
  11747. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11748. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11749. }
  11750. return this._emptyCubeTexture;
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Engine.prototype._rebuildInternalTextures = function () {
  11756. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11757. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11758. var internalTexture = currentState_1[_i];
  11759. internalTexture._rebuild();
  11760. }
  11761. };
  11762. Engine.prototype._rebuildEffects = function () {
  11763. for (var key in this._compiledEffects) {
  11764. var effect = this._compiledEffects[key];
  11765. effect._prepareEffect();
  11766. }
  11767. BABYLON.Effect.ResetCache();
  11768. };
  11769. Engine.prototype._rebuildBuffers = function () {
  11770. // Index / Vertex
  11771. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11772. var scene = _a[_i];
  11773. scene.resetCachedMaterial();
  11774. scene._rebuildGeometries();
  11775. scene._rebuildTextures();
  11776. }
  11777. // Uniforms
  11778. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11779. var uniformBuffer = _c[_b];
  11780. uniformBuffer._rebuild();
  11781. }
  11782. };
  11783. Engine.prototype._initGLContext = function () {
  11784. // Caps
  11785. this._caps = new EngineCapabilities();
  11786. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11787. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11788. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11789. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11790. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11791. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11792. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11793. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11794. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11795. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11796. // Infos
  11797. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11798. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11799. if (rendererInfo != null) {
  11800. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11801. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11802. }
  11803. if (!this._glVendor) {
  11804. this._glVendor = "Unknown vendor";
  11805. }
  11806. if (!this._glRenderer) {
  11807. this._glRenderer = "Unknown renderer";
  11808. }
  11809. // Constants
  11810. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11811. if (this._gl.RGBA16F !== 0x881A) {
  11812. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11813. }
  11814. if (this._gl.RGBA32F !== 0x8814) {
  11815. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11816. }
  11817. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11818. this._gl.DEPTH24_STENCIL8 = 35056;
  11819. }
  11820. // Extensions
  11821. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11822. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11823. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11824. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11825. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11826. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11827. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11828. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  11829. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11830. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11831. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11832. this._caps.highPrecisionShaderSupported = true;
  11833. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11834. if (this._caps.timerQuery) {
  11835. if (this._webGLVersion === 1) {
  11836. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11837. }
  11838. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11839. }
  11840. // Checks if some of the format renders first to allow the use of webgl inspector.
  11841. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11842. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11843. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11844. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11845. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11846. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11847. if (this._webGLVersion > 1) {
  11848. this._gl.HALF_FLOAT_OES = 0x140B;
  11849. }
  11850. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11851. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11852. // Draw buffers
  11853. if (this._webGLVersion > 1) {
  11854. this._caps.drawBuffersExtension = true;
  11855. }
  11856. else {
  11857. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11858. if (drawBuffersExtension !== null) {
  11859. this._caps.drawBuffersExtension = true;
  11860. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11861. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11862. for (var i = 0; i < 16; i++) {
  11863. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11864. }
  11865. }
  11866. else {
  11867. this._caps.drawBuffersExtension = false;
  11868. }
  11869. }
  11870. // Depth Texture
  11871. if (this._webGLVersion > 1) {
  11872. this._caps.depthTextureExtension = true;
  11873. }
  11874. else {
  11875. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11876. if (depthTextureExtension != null) {
  11877. this._caps.depthTextureExtension = true;
  11878. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11879. }
  11880. }
  11881. // Vertex array object
  11882. if (this._webGLVersion > 1) {
  11883. this._caps.vertexArrayObject = true;
  11884. }
  11885. else {
  11886. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11887. if (vertexArrayObjectExtension != null) {
  11888. this._caps.vertexArrayObject = true;
  11889. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11890. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11891. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11892. }
  11893. else {
  11894. this._caps.vertexArrayObject = false;
  11895. }
  11896. }
  11897. // Instances count
  11898. if (this._webGLVersion > 1) {
  11899. this._caps.instancedArrays = true;
  11900. }
  11901. else {
  11902. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11903. if (instanceExtension != null) {
  11904. this._caps.instancedArrays = true;
  11905. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11906. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11907. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11908. }
  11909. else {
  11910. this._caps.instancedArrays = false;
  11911. }
  11912. }
  11913. // Intelligently add supported compressed formats in order to check for.
  11914. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11915. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11916. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11917. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11918. if (this._caps.astc)
  11919. this.texturesSupported.push('-astc.ktx');
  11920. if (this._caps.s3tc)
  11921. this.texturesSupported.push('-dxt.ktx');
  11922. if (this._caps.pvrtc)
  11923. this.texturesSupported.push('-pvrtc.ktx');
  11924. if (this._caps.etc2)
  11925. this.texturesSupported.push('-etc2.ktx');
  11926. if (this._caps.etc1)
  11927. this.texturesSupported.push('-etc1.ktx');
  11928. if (this._gl.getShaderPrecisionFormat) {
  11929. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11930. if (highp) {
  11931. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11932. }
  11933. }
  11934. // Depth buffer
  11935. this.setDepthBuffer(true);
  11936. this.setDepthFunctionToLessOrEqual();
  11937. this.setDepthWrite(true);
  11938. // Texture maps
  11939. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11940. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11941. this._nextFreeTextureSlots.push(slot);
  11942. }
  11943. };
  11944. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11945. /**
  11946. * Gets version of the current webGL context
  11947. */
  11948. get: function () {
  11949. return this._webGLVersion;
  11950. },
  11951. enumerable: true,
  11952. configurable: true
  11953. });
  11954. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11955. /**
  11956. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11957. */
  11958. get: function () {
  11959. return this._isStencilEnable;
  11960. },
  11961. enumerable: true,
  11962. configurable: true
  11963. });
  11964. Engine.prototype._prepareWorkingCanvas = function () {
  11965. if (this._workingCanvas) {
  11966. return;
  11967. }
  11968. this._workingCanvas = document.createElement("canvas");
  11969. var context = this._workingCanvas.getContext("2d");
  11970. if (context) {
  11971. this._workingContext = context;
  11972. }
  11973. };
  11974. /**
  11975. * Reset the texture cache to empty state
  11976. */
  11977. Engine.prototype.resetTextureCache = function () {
  11978. for (var key in this._boundTexturesCache) {
  11979. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  11980. continue;
  11981. }
  11982. var boundTexture = this._boundTexturesCache[key];
  11983. if (boundTexture) {
  11984. this._removeDesignatedSlot(boundTexture);
  11985. }
  11986. this._boundTexturesCache[key] = null;
  11987. }
  11988. if (!this.disableTextureBindingOptimization) {
  11989. this._nextFreeTextureSlots = [];
  11990. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11991. this._nextFreeTextureSlots.push(slot);
  11992. }
  11993. }
  11994. this._currentTextureChannel = -1;
  11995. };
  11996. /**
  11997. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  11998. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  11999. * @returns true if engine is in deterministic lock step mode
  12000. */
  12001. Engine.prototype.isDeterministicLockStep = function () {
  12002. return this._deterministicLockstep;
  12003. };
  12004. /**
  12005. * Gets the max steps when engine is running in deterministic lock step
  12006. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12007. * @returns the max steps
  12008. */
  12009. Engine.prototype.getLockstepMaxSteps = function () {
  12010. return this._lockstepMaxSteps;
  12011. };
  12012. /**
  12013. * Gets an object containing information about the current webGL context
  12014. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12015. */
  12016. Engine.prototype.getGlInfo = function () {
  12017. return {
  12018. vendor: this._glVendor,
  12019. renderer: this._glRenderer,
  12020. version: this._glVersion
  12021. };
  12022. };
  12023. /**
  12024. * Gets current aspect ratio
  12025. * @param camera defines the camera to use to get the aspect ratio
  12026. * @param useScreen defines if screen size must be used (or the current render target if any)
  12027. * @returns a number defining the aspect ratio
  12028. */
  12029. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12030. if (useScreen === void 0) { useScreen = false; }
  12031. var viewport = camera.viewport;
  12032. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12033. };
  12034. /**
  12035. * Gets current screen aspect ratio
  12036. * @returns a number defining the aspect ratio
  12037. */
  12038. Engine.prototype.getScreenAspectRatio = function () {
  12039. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12040. };
  12041. /**
  12042. * Gets the current render width
  12043. * @param useScreen defines if screen size must be used (or the current render target if any)
  12044. * @returns a number defining the current render width
  12045. */
  12046. Engine.prototype.getRenderWidth = function (useScreen) {
  12047. if (useScreen === void 0) { useScreen = false; }
  12048. if (!useScreen && this._currentRenderTarget) {
  12049. return this._currentRenderTarget.width;
  12050. }
  12051. return this._gl.drawingBufferWidth;
  12052. };
  12053. /**
  12054. * Gets the current render height
  12055. * @param useScreen defines if screen size must be used (or the current render target if any)
  12056. * @returns a number defining the current render height
  12057. */
  12058. Engine.prototype.getRenderHeight = function (useScreen) {
  12059. if (useScreen === void 0) { useScreen = false; }
  12060. if (!useScreen && this._currentRenderTarget) {
  12061. return this._currentRenderTarget.height;
  12062. }
  12063. return this._gl.drawingBufferHeight;
  12064. };
  12065. /**
  12066. * Gets the HTML canvas attached with the current webGL context
  12067. * @returns a HTML canvas
  12068. */
  12069. Engine.prototype.getRenderingCanvas = function () {
  12070. return this._renderingCanvas;
  12071. };
  12072. /**
  12073. * Gets the client rect of the HTML canvas attached with the current webGL context
  12074. * @returns a client rectanglee
  12075. */
  12076. Engine.prototype.getRenderingCanvasClientRect = function () {
  12077. if (!this._renderingCanvas) {
  12078. return null;
  12079. }
  12080. return this._renderingCanvas.getBoundingClientRect();
  12081. };
  12082. /**
  12083. * Defines the hardware scaling level.
  12084. * By default the hardware scaling level is computed from the window device ratio.
  12085. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12086. * @param level defines the level to use
  12087. */
  12088. Engine.prototype.setHardwareScalingLevel = function (level) {
  12089. this._hardwareScalingLevel = level;
  12090. this.resize();
  12091. };
  12092. /**
  12093. * Gets the current hardware scaling level.
  12094. * By default the hardware scaling level is computed from the window device ratio.
  12095. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12096. * @returns a number indicating the current hardware scaling level
  12097. */
  12098. Engine.prototype.getHardwareScalingLevel = function () {
  12099. return this._hardwareScalingLevel;
  12100. };
  12101. /**
  12102. * Gets the list of loaded textures
  12103. * @returns an array containing all loaded textures
  12104. */
  12105. Engine.prototype.getLoadedTexturesCache = function () {
  12106. return this._internalTexturesCache;
  12107. };
  12108. /**
  12109. * Gets the object containing all engine capabilities
  12110. * @returns the EngineCapabilities object
  12111. */
  12112. Engine.prototype.getCaps = function () {
  12113. return this._caps;
  12114. };
  12115. Object.defineProperty(Engine.prototype, "drawCalls", {
  12116. /** @hidden */
  12117. get: function () {
  12118. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12119. return 0;
  12120. },
  12121. enumerable: true,
  12122. configurable: true
  12123. });
  12124. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12125. /** @hidden */
  12126. get: function () {
  12127. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12128. return null;
  12129. },
  12130. enumerable: true,
  12131. configurable: true
  12132. });
  12133. /**
  12134. * Gets the current depth function
  12135. * @returns a number defining the depth function
  12136. */
  12137. Engine.prototype.getDepthFunction = function () {
  12138. return this._depthCullingState.depthFunc;
  12139. };
  12140. /**
  12141. * Sets the current depth function
  12142. * @param depthFunc defines the function to use
  12143. */
  12144. Engine.prototype.setDepthFunction = function (depthFunc) {
  12145. this._depthCullingState.depthFunc = depthFunc;
  12146. };
  12147. /**
  12148. * Sets the current depth function to GREATER
  12149. */
  12150. Engine.prototype.setDepthFunctionToGreater = function () {
  12151. this._depthCullingState.depthFunc = this._gl.GREATER;
  12152. };
  12153. /**
  12154. * Sets the current depth function to GEQUAL
  12155. */
  12156. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12157. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12158. };
  12159. /**
  12160. * Sets the current depth function to LESS
  12161. */
  12162. Engine.prototype.setDepthFunctionToLess = function () {
  12163. this._depthCullingState.depthFunc = this._gl.LESS;
  12164. };
  12165. /**
  12166. * Sets the current depth function to LEQUAL
  12167. */
  12168. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12169. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12170. };
  12171. /**
  12172. * Gets a boolean indicating if stencil buffer is enabled
  12173. * @returns the current stencil buffer state
  12174. */
  12175. Engine.prototype.getStencilBuffer = function () {
  12176. return this._stencilState.stencilTest;
  12177. };
  12178. /**
  12179. * Enable or disable the stencil buffer
  12180. * @param enable defines if the stencil buffer must be enabled or disabled
  12181. */
  12182. Engine.prototype.setStencilBuffer = function (enable) {
  12183. this._stencilState.stencilTest = enable;
  12184. };
  12185. /**
  12186. * Gets the current stencil mask
  12187. * @returns a number defining the new stencil mask to use
  12188. */
  12189. Engine.prototype.getStencilMask = function () {
  12190. return this._stencilState.stencilMask;
  12191. };
  12192. /**
  12193. * Sets the current stencil mask
  12194. * @param mask defines the new stencil mask to use
  12195. */
  12196. Engine.prototype.setStencilMask = function (mask) {
  12197. this._stencilState.stencilMask = mask;
  12198. };
  12199. /**
  12200. * Gets the current stencil function
  12201. * @returns a number defining the stencil function to use
  12202. */
  12203. Engine.prototype.getStencilFunction = function () {
  12204. return this._stencilState.stencilFunc;
  12205. };
  12206. /**
  12207. * Gets the current stencil reference value
  12208. * @returns a number defining the stencil reference value to use
  12209. */
  12210. Engine.prototype.getStencilFunctionReference = function () {
  12211. return this._stencilState.stencilFuncRef;
  12212. };
  12213. /**
  12214. * Gets the current stencil mask
  12215. * @returns a number defining the stencil mask to use
  12216. */
  12217. Engine.prototype.getStencilFunctionMask = function () {
  12218. return this._stencilState.stencilFuncMask;
  12219. };
  12220. /**
  12221. * Sets the current stencil function
  12222. * @param stencilFunc defines the new stencil function to use
  12223. */
  12224. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12225. this._stencilState.stencilFunc = stencilFunc;
  12226. };
  12227. /**
  12228. * Sets the current stencil reference
  12229. * @param reference defines the new stencil reference to use
  12230. */
  12231. Engine.prototype.setStencilFunctionReference = function (reference) {
  12232. this._stencilState.stencilFuncRef = reference;
  12233. };
  12234. /**
  12235. * Sets the current stencil mask
  12236. * @param mask defines the new stencil mask to use
  12237. */
  12238. Engine.prototype.setStencilFunctionMask = function (mask) {
  12239. this._stencilState.stencilFuncMask = mask;
  12240. };
  12241. /**
  12242. * Gets the current stencil operation when stencil fails
  12243. * @returns a number defining stencil operation to use when stencil fails
  12244. */
  12245. Engine.prototype.getStencilOperationFail = function () {
  12246. return this._stencilState.stencilOpStencilFail;
  12247. };
  12248. /**
  12249. * Gets the current stencil operation when depth fails
  12250. * @returns a number defining stencil operation to use when depth fails
  12251. */
  12252. Engine.prototype.getStencilOperationDepthFail = function () {
  12253. return this._stencilState.stencilOpDepthFail;
  12254. };
  12255. /**
  12256. * Gets the current stencil operation when stencil passes
  12257. * @returns a number defining stencil operation to use when stencil passes
  12258. */
  12259. Engine.prototype.getStencilOperationPass = function () {
  12260. return this._stencilState.stencilOpStencilDepthPass;
  12261. };
  12262. /**
  12263. * Sets the stencil operation to use when stencil fails
  12264. * @param operation defines the stencil operation to use when stencil fails
  12265. */
  12266. Engine.prototype.setStencilOperationFail = function (operation) {
  12267. this._stencilState.stencilOpStencilFail = operation;
  12268. };
  12269. /**
  12270. * Sets the stencil operation to use when depth fails
  12271. * @param operation defines the stencil operation to use when depth fails
  12272. */
  12273. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12274. this._stencilState.stencilOpDepthFail = operation;
  12275. };
  12276. /**
  12277. * Sets the stencil operation to use when stencil passes
  12278. * @param operation defines the stencil operation to use when stencil passes
  12279. */
  12280. Engine.prototype.setStencilOperationPass = function (operation) {
  12281. this._stencilState.stencilOpStencilDepthPass = operation;
  12282. };
  12283. /**
  12284. * Sets a boolean indicating if the dithering state is enabled or disabled
  12285. * @param value defines the dithering state
  12286. */
  12287. Engine.prototype.setDitheringState = function (value) {
  12288. if (value) {
  12289. this._gl.enable(this._gl.DITHER);
  12290. }
  12291. else {
  12292. this._gl.disable(this._gl.DITHER);
  12293. }
  12294. };
  12295. /**
  12296. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12297. * @param value defines the rasterizer state
  12298. */
  12299. Engine.prototype.setRasterizerState = function (value) {
  12300. if (value) {
  12301. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12302. }
  12303. else {
  12304. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12305. }
  12306. };
  12307. /**
  12308. * stop executing a render loop function and remove it from the execution array
  12309. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12310. */
  12311. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12312. if (!renderFunction) {
  12313. this._activeRenderLoops = [];
  12314. return;
  12315. }
  12316. var index = this._activeRenderLoops.indexOf(renderFunction);
  12317. if (index >= 0) {
  12318. this._activeRenderLoops.splice(index, 1);
  12319. }
  12320. };
  12321. /** @hidden */
  12322. Engine.prototype._renderLoop = function () {
  12323. if (!this._contextWasLost) {
  12324. var shouldRender = true;
  12325. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12326. shouldRender = false;
  12327. }
  12328. if (shouldRender) {
  12329. // Start new frame
  12330. this.beginFrame();
  12331. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12332. var renderFunction = this._activeRenderLoops[index];
  12333. renderFunction();
  12334. }
  12335. // Present
  12336. this.endFrame();
  12337. }
  12338. }
  12339. if (this._activeRenderLoops.length > 0) {
  12340. // Register new frame
  12341. var requester = null;
  12342. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12343. requester = this._vrDisplay;
  12344. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12345. }
  12346. else {
  12347. this._renderingQueueLaunched = false;
  12348. }
  12349. };
  12350. /**
  12351. * Register and execute a render loop. The engine can have more than one render function
  12352. * @param renderFunction defines the function to continuously execute
  12353. */
  12354. Engine.prototype.runRenderLoop = function (renderFunction) {
  12355. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12356. return;
  12357. }
  12358. this._activeRenderLoops.push(renderFunction);
  12359. if (!this._renderingQueueLaunched) {
  12360. this._renderingQueueLaunched = true;
  12361. this._bindedRenderFunction = this._renderLoop.bind(this);
  12362. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12363. }
  12364. };
  12365. /**
  12366. * Toggle full screen mode
  12367. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12368. * @param options defines an option object to be sent to the requestFullscreen function
  12369. */
  12370. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12371. if (this.isFullscreen) {
  12372. BABYLON.Tools.ExitFullscreen();
  12373. }
  12374. else {
  12375. this._pointerLockRequested = requestPointerLock;
  12376. if (this._renderingCanvas) {
  12377. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12378. }
  12379. }
  12380. };
  12381. /**
  12382. * Clear the current render buffer or the current render target (if any is set up)
  12383. * @param color defines the color to use
  12384. * @param backBuffer defines if the back buffer must be cleared
  12385. * @param depth defines if the depth buffer must be cleared
  12386. * @param stencil defines if the stencil buffer must be cleared
  12387. */
  12388. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12389. if (stencil === void 0) { stencil = false; }
  12390. this.applyStates();
  12391. var mode = 0;
  12392. if (backBuffer && color) {
  12393. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12394. mode |= this._gl.COLOR_BUFFER_BIT;
  12395. }
  12396. if (depth) {
  12397. this._gl.clearDepth(1.0);
  12398. mode |= this._gl.DEPTH_BUFFER_BIT;
  12399. }
  12400. if (stencil) {
  12401. this._gl.clearStencil(0);
  12402. mode |= this._gl.STENCIL_BUFFER_BIT;
  12403. }
  12404. this._gl.clear(mode);
  12405. };
  12406. /**
  12407. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12408. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12409. * @param y defines the y-coordinate of the corner of the clear rectangle
  12410. * @param width defines the width of the clear rectangle
  12411. * @param height defines the height of the clear rectangle
  12412. * @param clearColor defines the clear color
  12413. */
  12414. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12415. var gl = this._gl;
  12416. // Save state
  12417. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12418. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12419. // Change state
  12420. gl.enable(gl.SCISSOR_TEST);
  12421. gl.scissor(x, y, width, height);
  12422. // Clear
  12423. this.clear(clearColor, true, true, true);
  12424. // Restore state
  12425. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12426. if (curScissor === true) {
  12427. gl.enable(gl.SCISSOR_TEST);
  12428. }
  12429. else {
  12430. gl.disable(gl.SCISSOR_TEST);
  12431. }
  12432. };
  12433. /** @hidden */
  12434. Engine.prototype._viewport = function (x, y, width, height) {
  12435. if (x !== this._viewportCached.x ||
  12436. y !== this._viewportCached.y ||
  12437. width !== this._viewportCached.z ||
  12438. height !== this._viewportCached.w) {
  12439. this._viewportCached.x = x;
  12440. this._viewportCached.y = y;
  12441. this._viewportCached.z = width;
  12442. this._viewportCached.w = height;
  12443. this._gl.viewport(x, y, width, height);
  12444. }
  12445. };
  12446. /**
  12447. * Set the WebGL's viewport
  12448. * @param viewport defines the viewport element to be used
  12449. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12450. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12451. */
  12452. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12453. var width = requiredWidth || this.getRenderWidth();
  12454. var height = requiredHeight || this.getRenderHeight();
  12455. var x = viewport.x || 0;
  12456. var y = viewport.y || 0;
  12457. this._cachedViewport = viewport;
  12458. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12459. };
  12460. /**
  12461. * Directly set the WebGL Viewport
  12462. * @param x defines the x coordinate of the viewport (in screen space)
  12463. * @param y defines the y coordinate of the viewport (in screen space)
  12464. * @param width defines the width of the viewport (in screen space)
  12465. * @param height defines the height of the viewport (in screen space)
  12466. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state
  12467. */
  12468. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12469. var currentViewport = this._cachedViewport;
  12470. this._cachedViewport = null;
  12471. this._viewport(x, y, width, height);
  12472. return currentViewport;
  12473. };
  12474. /**
  12475. * Begin a new frame
  12476. */
  12477. Engine.prototype.beginFrame = function () {
  12478. this.onBeginFrameObservable.notifyObservers(this);
  12479. this._measureFps();
  12480. };
  12481. /**
  12482. * Enf the current frame
  12483. */
  12484. Engine.prototype.endFrame = function () {
  12485. // Force a flush in case we are using a bad OS.
  12486. if (this._badOS) {
  12487. this.flushFramebuffer();
  12488. }
  12489. // Submit frame to the vr device, if enabled
  12490. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12491. // TODO: We should only submit the frame if we read frameData successfully.
  12492. this._vrDisplay.submitFrame();
  12493. }
  12494. this.onEndFrameObservable.notifyObservers(this);
  12495. };
  12496. /**
  12497. * Resize the view according to the canvas' size
  12498. */
  12499. Engine.prototype.resize = function () {
  12500. // We're not resizing the size of the canvas while in VR mode & presenting
  12501. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12502. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12503. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12504. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12505. }
  12506. };
  12507. /**
  12508. * Force a specific size of the canvas
  12509. * @param width defines the new canvas' width
  12510. * @param height defines the new canvas' height
  12511. */
  12512. Engine.prototype.setSize = function (width, height) {
  12513. if (!this._renderingCanvas) {
  12514. return;
  12515. }
  12516. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12517. return;
  12518. }
  12519. this._renderingCanvas.width = width;
  12520. this._renderingCanvas.height = height;
  12521. for (var index = 0; index < this.scenes.length; index++) {
  12522. var scene = this.scenes[index];
  12523. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12524. var cam = scene.cameras[camIndex];
  12525. cam._currentRenderId = 0;
  12526. }
  12527. }
  12528. if (this.onResizeObservable.hasObservers) {
  12529. this.onResizeObservable.notifyObservers(this);
  12530. }
  12531. };
  12532. // WebVR functions
  12533. /**
  12534. * Gets a boolean indicating if a webVR device was detected
  12535. * @returns true if a webVR device was detected
  12536. */
  12537. Engine.prototype.isVRDevicePresent = function () {
  12538. return !!this._vrDisplay;
  12539. };
  12540. /**
  12541. * Gets the current webVR device
  12542. * @returns the current webVR device (or null)
  12543. */
  12544. Engine.prototype.getVRDevice = function () {
  12545. return this._vrDisplay;
  12546. };
  12547. /**
  12548. * Initializes a webVR display and starts listening to display change events
  12549. * The onVRDisplayChangedObservable will be notified upon these changes
  12550. * @returns The onVRDisplayChangedObservable
  12551. */
  12552. Engine.prototype.initWebVR = function () {
  12553. this.initWebVRAsync();
  12554. return this.onVRDisplayChangedObservable;
  12555. };
  12556. /**
  12557. * Initializes a webVR display and starts listening to display change events
  12558. * The onVRDisplayChangedObservable will be notified upon these changes
  12559. * @returns A promise containing a VRDisplay and if vr is supported
  12560. */
  12561. Engine.prototype.initWebVRAsync = function () {
  12562. var _this = this;
  12563. var notifyObservers = function () {
  12564. var eventArgs = {
  12565. vrDisplay: _this._vrDisplay,
  12566. vrSupported: _this._vrSupported
  12567. };
  12568. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12569. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12570. };
  12571. if (!this._onVrDisplayConnect) {
  12572. this._onVrDisplayConnect = function (event) {
  12573. _this._vrDisplay = event.display;
  12574. notifyObservers();
  12575. };
  12576. this._onVrDisplayDisconnect = function () {
  12577. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12578. _this._vrDisplay = undefined;
  12579. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12580. notifyObservers();
  12581. };
  12582. this._onVrDisplayPresentChange = function () {
  12583. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12584. };
  12585. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12586. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12587. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12588. }
  12589. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12590. this._webVRInitPromise.then(notifyObservers);
  12591. return this._webVRInitPromise;
  12592. };
  12593. /**
  12594. * Call this function to switch to webVR mode
  12595. * Will do nothing if webVR is not supported or if there is no webVR device
  12596. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12597. */
  12598. Engine.prototype.enableVR = function () {
  12599. var _this = this;
  12600. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12601. var onResolved = function () {
  12602. _this.onVRRequestPresentComplete.notifyObservers(true);
  12603. _this._onVRFullScreenTriggered();
  12604. };
  12605. var onRejected = function () {
  12606. _this.onVRRequestPresentComplete.notifyObservers(false);
  12607. };
  12608. this.onVRRequestPresentStart.notifyObservers(this);
  12609. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12610. }
  12611. };
  12612. /**
  12613. * Call this function to leave webVR mode
  12614. * Will do nothing if webVR is not supported or if there is no webVR device
  12615. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12616. */
  12617. Engine.prototype.disableVR = function () {
  12618. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12619. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12620. }
  12621. };
  12622. Engine.prototype._getVRDisplaysAsync = function () {
  12623. var _this = this;
  12624. return new Promise(function (res, rej) {
  12625. if (navigator.getVRDisplays) {
  12626. navigator.getVRDisplays().then(function (devices) {
  12627. _this._vrSupported = true;
  12628. // note that devices may actually be an empty array. This is fine;
  12629. // we expect this._vrDisplay to be undefined in this case.
  12630. _this._vrDisplay = devices[0];
  12631. res({
  12632. vrDisplay: _this._vrDisplay,
  12633. vrSupported: _this._vrSupported
  12634. });
  12635. });
  12636. }
  12637. else {
  12638. _this._vrDisplay = undefined;
  12639. _this._vrSupported = false;
  12640. res({
  12641. vrDisplay: _this._vrDisplay,
  12642. vrSupported: _this._vrSupported
  12643. });
  12644. }
  12645. });
  12646. };
  12647. /**
  12648. * Binds the frame buffer to the specified texture.
  12649. * @param texture The texture to render to or null for the default canvas
  12650. * @param faceIndex The face of the texture to render to in case of cube texture
  12651. * @param requiredWidth The width of the target to render to
  12652. * @param requiredHeight The height of the target to render to
  12653. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12654. * @param depthStencilTexture The depth stencil texture to use to render
  12655. * @param lodLevel defines le lod level to bind to the frame buffer
  12656. */
  12657. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12658. if (lodLevel === void 0) { lodLevel = 0; }
  12659. if (this._currentRenderTarget) {
  12660. this.unBindFramebuffer(this._currentRenderTarget);
  12661. }
  12662. this._currentRenderTarget = texture;
  12663. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12664. var gl = this._gl;
  12665. if (texture.isCube) {
  12666. if (faceIndex === undefined) {
  12667. faceIndex = 0;
  12668. }
  12669. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12670. if (depthStencilTexture) {
  12671. if (depthStencilTexture._generateStencilBuffer) {
  12672. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12673. }
  12674. else {
  12675. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12676. }
  12677. }
  12678. }
  12679. if (this._cachedViewport && !forceFullscreenViewport) {
  12680. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12681. }
  12682. else {
  12683. if (!requiredWidth) {
  12684. requiredWidth = texture.width;
  12685. if (lodLevel) {
  12686. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12687. }
  12688. }
  12689. if (!requiredHeight) {
  12690. requiredHeight = texture.height;
  12691. if (lodLevel) {
  12692. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12693. }
  12694. }
  12695. this._viewport(0, 0, requiredWidth, requiredHeight);
  12696. }
  12697. this.wipeCaches();
  12698. };
  12699. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12700. if (this._currentFramebuffer !== framebuffer) {
  12701. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12702. this._currentFramebuffer = framebuffer;
  12703. }
  12704. };
  12705. /**
  12706. * Unbind the current render target texture from the webGL context
  12707. * @param texture defines the render target texture to unbind
  12708. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12709. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12710. */
  12711. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12712. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12713. this._currentRenderTarget = null;
  12714. // If MSAA, we need to bitblt back to main texture
  12715. var gl = this._gl;
  12716. if (texture._MSAAFramebuffer) {
  12717. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12718. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12719. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12720. }
  12721. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12722. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12723. gl.generateMipmap(gl.TEXTURE_2D);
  12724. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12725. }
  12726. if (onBeforeUnbind) {
  12727. if (texture._MSAAFramebuffer) {
  12728. // Bind the correct framebuffer
  12729. this.bindUnboundFramebuffer(texture._framebuffer);
  12730. }
  12731. onBeforeUnbind();
  12732. }
  12733. this.bindUnboundFramebuffer(null);
  12734. };
  12735. /**
  12736. * Unbind a list of render target textures from the webGL context
  12737. * This is used only when drawBuffer extension or webGL2 are active
  12738. * @param textures defines the render target textures to unbind
  12739. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12740. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12741. */
  12742. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12743. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12744. this._currentRenderTarget = null;
  12745. // If MSAA, we need to bitblt back to main texture
  12746. var gl = this._gl;
  12747. if (textures[0]._MSAAFramebuffer) {
  12748. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12749. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12750. var attachments = textures[0]._attachments;
  12751. if (!attachments) {
  12752. attachments = new Array(textures.length);
  12753. textures[0]._attachments = attachments;
  12754. }
  12755. for (var i = 0; i < textures.length; i++) {
  12756. var texture = textures[i];
  12757. for (var j = 0; j < attachments.length; j++) {
  12758. attachments[j] = gl.NONE;
  12759. }
  12760. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12761. gl.readBuffer(attachments[i]);
  12762. gl.drawBuffers(attachments);
  12763. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12764. }
  12765. for (var i = 0; i < attachments.length; i++) {
  12766. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12767. }
  12768. gl.drawBuffers(attachments);
  12769. }
  12770. for (var i = 0; i < textures.length; i++) {
  12771. var texture = textures[i];
  12772. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12773. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12774. gl.generateMipmap(gl.TEXTURE_2D);
  12775. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12776. }
  12777. }
  12778. if (onBeforeUnbind) {
  12779. if (textures[0]._MSAAFramebuffer) {
  12780. // Bind the correct framebuffer
  12781. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12782. }
  12783. onBeforeUnbind();
  12784. }
  12785. this.bindUnboundFramebuffer(null);
  12786. };
  12787. /**
  12788. * Force the mipmap generation for the given render target texture
  12789. * @param texture defines the render target texture to use
  12790. */
  12791. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12792. if (texture.generateMipMaps) {
  12793. var gl = this._gl;
  12794. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12795. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12796. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12797. }
  12798. };
  12799. /**
  12800. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12801. */
  12802. Engine.prototype.flushFramebuffer = function () {
  12803. this._gl.flush();
  12804. };
  12805. /**
  12806. * Unbind the current render target and bind the default framebuffer
  12807. */
  12808. Engine.prototype.restoreDefaultFramebuffer = function () {
  12809. if (this._currentRenderTarget) {
  12810. this.unBindFramebuffer(this._currentRenderTarget);
  12811. }
  12812. else {
  12813. this.bindUnboundFramebuffer(null);
  12814. }
  12815. if (this._cachedViewport) {
  12816. this.setViewport(this._cachedViewport);
  12817. }
  12818. this.wipeCaches();
  12819. };
  12820. // UBOs
  12821. /**
  12822. * Create an uniform buffer
  12823. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12824. * @param elements defines the content of the uniform buffer
  12825. * @returns the webGL uniform buffer
  12826. */
  12827. Engine.prototype.createUniformBuffer = function (elements) {
  12828. var ubo = this._gl.createBuffer();
  12829. if (!ubo) {
  12830. throw new Error("Unable to create uniform buffer");
  12831. }
  12832. this.bindUniformBuffer(ubo);
  12833. if (elements instanceof Float32Array) {
  12834. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12835. }
  12836. else {
  12837. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12838. }
  12839. this.bindUniformBuffer(null);
  12840. ubo.references = 1;
  12841. return ubo;
  12842. };
  12843. /**
  12844. * Create a dynamic uniform buffer
  12845. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12846. * @param elements defines the content of the uniform buffer
  12847. * @returns the webGL uniform buffer
  12848. */
  12849. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12850. var ubo = this._gl.createBuffer();
  12851. if (!ubo) {
  12852. throw new Error("Unable to create dynamic uniform buffer");
  12853. }
  12854. this.bindUniformBuffer(ubo);
  12855. if (elements instanceof Float32Array) {
  12856. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12857. }
  12858. else {
  12859. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12860. }
  12861. this.bindUniformBuffer(null);
  12862. ubo.references = 1;
  12863. return ubo;
  12864. };
  12865. /**
  12866. * Update an existing uniform buffer
  12867. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12868. * @param uniformBuffer defines the target uniform buffer
  12869. * @param elements defines the content to update
  12870. * @param offset defines the offset in the uniform buffer where update should start
  12871. * @param count defines the size of the data to update
  12872. */
  12873. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12874. this.bindUniformBuffer(uniformBuffer);
  12875. if (offset === undefined) {
  12876. offset = 0;
  12877. }
  12878. if (count === undefined) {
  12879. if (elements instanceof Float32Array) {
  12880. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12881. }
  12882. else {
  12883. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12884. }
  12885. }
  12886. else {
  12887. if (elements instanceof Float32Array) {
  12888. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12889. }
  12890. else {
  12891. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12892. }
  12893. }
  12894. this.bindUniformBuffer(null);
  12895. };
  12896. // VBOs
  12897. Engine.prototype._resetVertexBufferBinding = function () {
  12898. this.bindArrayBuffer(null);
  12899. this._cachedVertexBuffers = null;
  12900. };
  12901. /**
  12902. * Creates a vertex buffer
  12903. * @param data the data for the vertex buffer
  12904. * @returns the new WebGL static buffer
  12905. */
  12906. Engine.prototype.createVertexBuffer = function (data) {
  12907. var vbo = this._gl.createBuffer();
  12908. if (!vbo) {
  12909. throw new Error("Unable to create vertex buffer");
  12910. }
  12911. this.bindArrayBuffer(vbo);
  12912. if (data instanceof Array) {
  12913. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  12914. }
  12915. else {
  12916. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  12917. }
  12918. this._resetVertexBufferBinding();
  12919. vbo.references = 1;
  12920. return vbo;
  12921. };
  12922. /**
  12923. * Creates a dynamic vertex buffer
  12924. * @param data the data for the dynamic vertex buffer
  12925. * @returns the new WebGL dynamic buffer
  12926. */
  12927. Engine.prototype.createDynamicVertexBuffer = function (data) {
  12928. var vbo = this._gl.createBuffer();
  12929. if (!vbo) {
  12930. throw new Error("Unable to create dynamic vertex buffer");
  12931. }
  12932. this.bindArrayBuffer(vbo);
  12933. if (data instanceof Array) {
  12934. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  12935. }
  12936. else {
  12937. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  12938. }
  12939. this._resetVertexBufferBinding();
  12940. vbo.references = 1;
  12941. return vbo;
  12942. };
  12943. /**
  12944. * Update a dynamic index buffer
  12945. * @param indexBuffer defines the target index buffer
  12946. * @param indices defines the data to update
  12947. * @param offset defines the offset in the target index buffer where update should start
  12948. */
  12949. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12950. if (offset === void 0) { offset = 0; }
  12951. // Force cache update
  12952. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12953. this.bindIndexBuffer(indexBuffer);
  12954. var arrayBuffer;
  12955. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12956. arrayBuffer = indices;
  12957. }
  12958. else {
  12959. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12960. }
  12961. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12962. this._resetIndexBufferBinding();
  12963. };
  12964. /**
  12965. * Updates a dynamic vertex buffer.
  12966. * @param vertexBuffer the vertex buffer to update
  12967. * @param data the data used to update the vertex buffer
  12968. * @param byteOffset the byte offset of the data
  12969. * @param byteLength the byte length of the data
  12970. */
  12971. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  12972. this.bindArrayBuffer(vertexBuffer);
  12973. if (byteOffset === undefined) {
  12974. byteOffset = 0;
  12975. }
  12976. if (byteLength === undefined) {
  12977. if (data instanceof Array) {
  12978. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  12979. }
  12980. else {
  12981. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  12982. }
  12983. }
  12984. else {
  12985. if (data instanceof Array) {
  12986. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  12987. }
  12988. else {
  12989. if (data instanceof ArrayBuffer) {
  12990. data = new Uint8Array(data, byteOffset, byteLength);
  12991. }
  12992. else {
  12993. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  12994. }
  12995. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12996. }
  12997. }
  12998. this._resetVertexBufferBinding();
  12999. };
  13000. Engine.prototype._resetIndexBufferBinding = function () {
  13001. this.bindIndexBuffer(null);
  13002. this._cachedIndexBuffer = null;
  13003. };
  13004. /**
  13005. * Creates a new index buffer
  13006. * @param indices defines the content of the index buffer
  13007. * @param updatable defines if the index buffer must be updatable
  13008. * @returns a new webGL buffer
  13009. */
  13010. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13011. var vbo = this._gl.createBuffer();
  13012. if (!vbo) {
  13013. throw new Error("Unable to create index buffer");
  13014. }
  13015. this.bindIndexBuffer(vbo);
  13016. // Check for 32 bits indices
  13017. var arrayBuffer;
  13018. var need32Bits = false;
  13019. if (indices instanceof Uint16Array) {
  13020. arrayBuffer = indices;
  13021. }
  13022. else {
  13023. //check 32 bit support
  13024. if (this._caps.uintIndices) {
  13025. if (indices instanceof Uint32Array) {
  13026. arrayBuffer = indices;
  13027. need32Bits = true;
  13028. }
  13029. else {
  13030. //number[] or Int32Array, check if 32 bit is necessary
  13031. for (var index = 0; index < indices.length; index++) {
  13032. if (indices[index] > 65535) {
  13033. need32Bits = true;
  13034. break;
  13035. }
  13036. }
  13037. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13038. }
  13039. }
  13040. else {
  13041. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13042. arrayBuffer = new Uint16Array(indices);
  13043. }
  13044. }
  13045. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13046. this._resetIndexBufferBinding();
  13047. vbo.references = 1;
  13048. vbo.is32Bits = need32Bits;
  13049. return vbo;
  13050. };
  13051. /**
  13052. * Bind a webGL buffer to the webGL context
  13053. * @param buffer defines the buffer to bind
  13054. */
  13055. Engine.prototype.bindArrayBuffer = function (buffer) {
  13056. if (!this._vaoRecordInProgress) {
  13057. this._unbindVertexArrayObject();
  13058. }
  13059. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13060. };
  13061. /**
  13062. * Bind an uniform buffer to the current webGL context
  13063. * @param buffer defines the buffer to bind
  13064. */
  13065. Engine.prototype.bindUniformBuffer = function (buffer) {
  13066. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13067. };
  13068. /**
  13069. * Bind a buffer to the current webGL context at a given location
  13070. * @param buffer defines the buffer to bind
  13071. * @param location defines the index where to bind the buffer
  13072. */
  13073. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13074. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13075. };
  13076. /**
  13077. * Bind a specific block at a given index in a specific shader program
  13078. * @param shaderProgram defines the shader program
  13079. * @param blockName defines the block name
  13080. * @param index defines the index where to bind the block
  13081. */
  13082. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13083. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13084. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13085. };
  13086. ;
  13087. Engine.prototype.bindIndexBuffer = function (buffer) {
  13088. if (!this._vaoRecordInProgress) {
  13089. this._unbindVertexArrayObject();
  13090. }
  13091. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13092. };
  13093. Engine.prototype.bindBuffer = function (buffer, target) {
  13094. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13095. this._gl.bindBuffer(target, buffer);
  13096. this._currentBoundBuffer[target] = buffer;
  13097. }
  13098. };
  13099. /**
  13100. * update the bound buffer with the given data
  13101. * @param data defines the data to update
  13102. */
  13103. Engine.prototype.updateArrayBuffer = function (data) {
  13104. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13105. };
  13106. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13107. var pointer = this._currentBufferPointers[indx];
  13108. var changed = false;
  13109. if (!pointer.active) {
  13110. changed = true;
  13111. pointer.active = true;
  13112. pointer.index = indx;
  13113. pointer.size = size;
  13114. pointer.type = type;
  13115. pointer.normalized = normalized;
  13116. pointer.stride = stride;
  13117. pointer.offset = offset;
  13118. pointer.buffer = buffer;
  13119. }
  13120. else {
  13121. if (pointer.buffer !== buffer) {
  13122. pointer.buffer = buffer;
  13123. changed = true;
  13124. }
  13125. if (pointer.size !== size) {
  13126. pointer.size = size;
  13127. changed = true;
  13128. }
  13129. if (pointer.type !== type) {
  13130. pointer.type = type;
  13131. changed = true;
  13132. }
  13133. if (pointer.normalized !== normalized) {
  13134. pointer.normalized = normalized;
  13135. changed = true;
  13136. }
  13137. if (pointer.stride !== stride) {
  13138. pointer.stride = stride;
  13139. changed = true;
  13140. }
  13141. if (pointer.offset !== offset) {
  13142. pointer.offset = offset;
  13143. changed = true;
  13144. }
  13145. }
  13146. if (changed || this._vaoRecordInProgress) {
  13147. this.bindArrayBuffer(buffer);
  13148. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13149. }
  13150. };
  13151. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13152. if (indexBuffer == null) {
  13153. return;
  13154. }
  13155. if (this._cachedIndexBuffer !== indexBuffer) {
  13156. this._cachedIndexBuffer = indexBuffer;
  13157. this.bindIndexBuffer(indexBuffer);
  13158. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13159. }
  13160. };
  13161. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13162. var attributes = effect.getAttributesNames();
  13163. if (!this._vaoRecordInProgress) {
  13164. this._unbindVertexArrayObject();
  13165. }
  13166. this.unbindAllAttributes();
  13167. for (var index = 0; index < attributes.length; index++) {
  13168. var order = effect.getAttributeLocation(index);
  13169. if (order >= 0) {
  13170. var vertexBuffer = vertexBuffers[attributes[index]];
  13171. if (!vertexBuffer) {
  13172. continue;
  13173. }
  13174. this._gl.enableVertexAttribArray(order);
  13175. if (!this._vaoRecordInProgress) {
  13176. this._vertexAttribArraysEnabled[order] = true;
  13177. }
  13178. var buffer = vertexBuffer.getBuffer();
  13179. if (buffer) {
  13180. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13181. if (vertexBuffer.getIsInstanced()) {
  13182. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13183. if (!this._vaoRecordInProgress) {
  13184. this._currentInstanceLocations.push(order);
  13185. this._currentInstanceBuffers.push(buffer);
  13186. }
  13187. }
  13188. }
  13189. }
  13190. }
  13191. };
  13192. /**
  13193. * Records a vertex array object
  13194. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13195. * @param vertexBuffers defines the list of vertex buffers to store
  13196. * @param indexBuffer defines the index buffer to store
  13197. * @param effect defines the effect to store
  13198. * @returns the new vertex array object
  13199. */
  13200. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13201. var vao = this._gl.createVertexArray();
  13202. this._vaoRecordInProgress = true;
  13203. this._gl.bindVertexArray(vao);
  13204. this._mustWipeVertexAttributes = true;
  13205. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13206. this.bindIndexBuffer(indexBuffer);
  13207. this._vaoRecordInProgress = false;
  13208. this._gl.bindVertexArray(null);
  13209. return vao;
  13210. };
  13211. /**
  13212. * Bind a specific vertex array object
  13213. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13214. * @param vertexArrayObject defines the vertex array object to bind
  13215. * @param indexBuffer defines the index buffer to bind
  13216. */
  13217. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13218. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13219. this._cachedVertexArrayObject = vertexArrayObject;
  13220. this._gl.bindVertexArray(vertexArrayObject);
  13221. this._cachedVertexBuffers = null;
  13222. this._cachedIndexBuffer = null;
  13223. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13224. this._mustWipeVertexAttributes = true;
  13225. }
  13226. };
  13227. /**
  13228. * Bind webGl buffers directly to the webGL context
  13229. * @param vertexBuffer defines the vertex buffer to bind
  13230. * @param indexBuffer defines the index buffer to bind
  13231. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13232. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13233. * @param effect defines the effect associated with the vertex buffer
  13234. */
  13235. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13236. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13237. this._cachedVertexBuffers = vertexBuffer;
  13238. this._cachedEffectForVertexBuffers = effect;
  13239. var attributesCount = effect.getAttributesCount();
  13240. this._unbindVertexArrayObject();
  13241. this.unbindAllAttributes();
  13242. var offset = 0;
  13243. for (var index = 0; index < attributesCount; index++) {
  13244. if (index < vertexDeclaration.length) {
  13245. var order = effect.getAttributeLocation(index);
  13246. if (order >= 0) {
  13247. this._gl.enableVertexAttribArray(order);
  13248. this._vertexAttribArraysEnabled[order] = true;
  13249. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13250. }
  13251. offset += vertexDeclaration[index] * 4;
  13252. }
  13253. }
  13254. }
  13255. this._bindIndexBufferWithCache(indexBuffer);
  13256. };
  13257. Engine.prototype._unbindVertexArrayObject = function () {
  13258. if (!this._cachedVertexArrayObject) {
  13259. return;
  13260. }
  13261. this._cachedVertexArrayObject = null;
  13262. this._gl.bindVertexArray(null);
  13263. };
  13264. /**
  13265. * Bind a list of vertex buffers to the webGL context
  13266. * @param vertexBuffers defines the list of vertex buffers to bind
  13267. * @param indexBuffer defines the index buffer to bind
  13268. * @param effect defines the effect associated with the vertex buffers
  13269. */
  13270. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13271. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13272. this._cachedVertexBuffers = vertexBuffers;
  13273. this._cachedEffectForVertexBuffers = effect;
  13274. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13275. }
  13276. this._bindIndexBufferWithCache(indexBuffer);
  13277. };
  13278. /**
  13279. * Unbind all instance attributes
  13280. */
  13281. Engine.prototype.unbindInstanceAttributes = function () {
  13282. var boundBuffer;
  13283. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13284. var instancesBuffer = this._currentInstanceBuffers[i];
  13285. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13286. boundBuffer = instancesBuffer;
  13287. this.bindArrayBuffer(instancesBuffer);
  13288. }
  13289. var offsetLocation = this._currentInstanceLocations[i];
  13290. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13291. }
  13292. this._currentInstanceBuffers.length = 0;
  13293. this._currentInstanceLocations.length = 0;
  13294. };
  13295. /**
  13296. * Release and free the memory of a vertex array object
  13297. * @param vao defines the vertex array object to delete
  13298. */
  13299. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13300. this._gl.deleteVertexArray(vao);
  13301. };
  13302. /** @hidden */
  13303. Engine.prototype._releaseBuffer = function (buffer) {
  13304. buffer.references--;
  13305. if (buffer.references === 0) {
  13306. this._gl.deleteBuffer(buffer);
  13307. return true;
  13308. }
  13309. return false;
  13310. };
  13311. /**
  13312. * Creates a webGL buffer to use with instanciation
  13313. * @param capacity defines the size of the buffer
  13314. * @returns the webGL buffer
  13315. */
  13316. Engine.prototype.createInstancesBuffer = function (capacity) {
  13317. var buffer = this._gl.createBuffer();
  13318. if (!buffer) {
  13319. throw new Error("Unable to create instance buffer");
  13320. }
  13321. buffer.capacity = capacity;
  13322. this.bindArrayBuffer(buffer);
  13323. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13324. return buffer;
  13325. };
  13326. /**
  13327. * Delete a webGL buffer used with instanciation
  13328. * @param buffer defines the webGL buffer to delete
  13329. */
  13330. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13331. this._gl.deleteBuffer(buffer);
  13332. };
  13333. /**
  13334. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13335. * @param instancesBuffer defines the webGL buffer to update and bind
  13336. * @param data defines the data to store in the buffer
  13337. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13338. */
  13339. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13340. this.bindArrayBuffer(instancesBuffer);
  13341. if (data) {
  13342. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13343. }
  13344. if (offsetLocations[0].index !== undefined) {
  13345. var stride = 0;
  13346. for (var i = 0; i < offsetLocations.length; i++) {
  13347. var ai = offsetLocations[i];
  13348. stride += ai.attributeSize * 4;
  13349. }
  13350. for (var i = 0; i < offsetLocations.length; i++) {
  13351. var ai = offsetLocations[i];
  13352. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13353. this._gl.enableVertexAttribArray(ai.index);
  13354. this._vertexAttribArraysEnabled[ai.index] = true;
  13355. }
  13356. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13357. this._gl.vertexAttribDivisor(ai.index, 1);
  13358. this._currentInstanceLocations.push(ai.index);
  13359. this._currentInstanceBuffers.push(instancesBuffer);
  13360. }
  13361. }
  13362. else {
  13363. for (var index = 0; index < 4; index++) {
  13364. var offsetLocation = offsetLocations[index];
  13365. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13366. this._gl.enableVertexAttribArray(offsetLocation);
  13367. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13368. }
  13369. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13370. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13371. this._currentInstanceLocations.push(offsetLocation);
  13372. this._currentInstanceBuffers.push(instancesBuffer);
  13373. }
  13374. }
  13375. };
  13376. /**
  13377. * Apply all cached states (depth, culling, stencil and alpha)
  13378. */
  13379. Engine.prototype.applyStates = function () {
  13380. this._depthCullingState.apply(this._gl);
  13381. this._stencilState.apply(this._gl);
  13382. this._alphaState.apply(this._gl);
  13383. };
  13384. /**
  13385. * Send a draw order
  13386. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13387. * @param indexStart defines the starting index
  13388. * @param indexCount defines the number of index to draw
  13389. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13390. */
  13391. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13392. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13393. };
  13394. /**
  13395. * Draw a list of points
  13396. * @param verticesStart defines the index of first vertex to draw
  13397. * @param verticesCount defines the count of vertices to draw
  13398. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13399. */
  13400. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13401. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13402. };
  13403. /**
  13404. * Draw a list of unindexed primitives
  13405. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13406. * @param verticesStart defines the index of first vertex to draw
  13407. * @param verticesCount defines the count of vertices to draw
  13408. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13409. */
  13410. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13411. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13412. };
  13413. /**
  13414. * Draw a list of indexed primitives
  13415. * @param fillMode defines the primitive to use
  13416. * @param indexStart defines the starting index
  13417. * @param indexCount defines the number of index to draw
  13418. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13419. */
  13420. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13421. // Apply states
  13422. this.applyStates();
  13423. this._drawCalls.addCount(1, false);
  13424. // Render
  13425. var drawMode = this._drawMode(fillMode);
  13426. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13427. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13428. if (instancesCount) {
  13429. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13430. }
  13431. else {
  13432. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13433. }
  13434. };
  13435. /**
  13436. * Draw a list of unindexed primitives
  13437. * @param fillMode defines the primitive to use
  13438. * @param verticesStart defines the index of first vertex to draw
  13439. * @param verticesCount defines the count of vertices to draw
  13440. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13441. */
  13442. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13443. // Apply states
  13444. this.applyStates();
  13445. this._drawCalls.addCount(1, false);
  13446. var drawMode = this._drawMode(fillMode);
  13447. if (instancesCount) {
  13448. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13449. }
  13450. else {
  13451. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13452. }
  13453. };
  13454. Engine.prototype._drawMode = function (fillMode) {
  13455. switch (fillMode) {
  13456. // Triangle views
  13457. case BABYLON.Material.TriangleFillMode:
  13458. return this._gl.TRIANGLES;
  13459. case BABYLON.Material.PointFillMode:
  13460. return this._gl.POINTS;
  13461. case BABYLON.Material.WireFrameFillMode:
  13462. return this._gl.LINES;
  13463. // Draw modes
  13464. case BABYLON.Material.PointListDrawMode:
  13465. return this._gl.POINTS;
  13466. case BABYLON.Material.LineListDrawMode:
  13467. return this._gl.LINES;
  13468. case BABYLON.Material.LineLoopDrawMode:
  13469. return this._gl.LINE_LOOP;
  13470. case BABYLON.Material.LineStripDrawMode:
  13471. return this._gl.LINE_STRIP;
  13472. case BABYLON.Material.TriangleStripDrawMode:
  13473. return this._gl.TRIANGLE_STRIP;
  13474. case BABYLON.Material.TriangleFanDrawMode:
  13475. return this._gl.TRIANGLE_FAN;
  13476. default:
  13477. return this._gl.TRIANGLES;
  13478. }
  13479. };
  13480. // Shaders
  13481. /** @hidden */
  13482. Engine.prototype._releaseEffect = function (effect) {
  13483. if (this._compiledEffects[effect._key]) {
  13484. delete this._compiledEffects[effect._key];
  13485. this._deleteProgram(effect.getProgram());
  13486. }
  13487. };
  13488. /** @hidden */
  13489. Engine.prototype._deleteProgram = function (program) {
  13490. if (program) {
  13491. program.__SPECTOR_rebuildProgram = null;
  13492. if (program.transformFeedback) {
  13493. this.deleteTransformFeedback(program.transformFeedback);
  13494. program.transformFeedback = null;
  13495. }
  13496. this._gl.deleteProgram(program);
  13497. }
  13498. };
  13499. /**
  13500. * Create a new effect (used to store vertex/fragment shaders)
  13501. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13502. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13503. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13504. * @param samplers defines an array of string used to represent textures
  13505. * @param defines defines the string containing the defines to use to compile the shaders
  13506. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13507. * @param onCompiled defines a function to call when the effect creation is successful
  13508. * @param onError defines a function to call when the effect creation has failed
  13509. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13510. * @returns the new Effect
  13511. */
  13512. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13513. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13514. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13515. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13516. if (this._compiledEffects[name]) {
  13517. var compiledEffect = this._compiledEffects[name];
  13518. if (onCompiled && compiledEffect.isReady()) {
  13519. onCompiled(compiledEffect);
  13520. }
  13521. return compiledEffect;
  13522. }
  13523. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13524. effect._key = name;
  13525. this._compiledEffects[name] = effect;
  13526. return effect;
  13527. };
  13528. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13529. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13530. };
  13531. ;
  13532. Engine.prototype._compileRawShader = function (source, type) {
  13533. var gl = this._gl;
  13534. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13535. gl.shaderSource(shader, source);
  13536. gl.compileShader(shader);
  13537. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13538. var log = gl.getShaderInfoLog(shader);
  13539. if (log) {
  13540. throw new Error(log);
  13541. }
  13542. }
  13543. if (!shader) {
  13544. throw new Error("Something went wrong while compile the shader.");
  13545. }
  13546. return shader;
  13547. };
  13548. ;
  13549. /**
  13550. * Directly creates a webGL program
  13551. * @param vertexCode defines the vertex shader code to use
  13552. * @param fragmentCode defines the fragment shader code to use
  13553. * @param context defines the webGL context to use (if not set, the current one will be used)
  13554. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13555. * @returns the new webGL program
  13556. */
  13557. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13558. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13559. context = context || this._gl;
  13560. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13561. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13562. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13563. };
  13564. /**
  13565. * Creates a webGL program
  13566. * @param vertexCode defines the vertex shader code to use
  13567. * @param fragmentCode defines the fragment shader code to use
  13568. * @param defines defines the string containing the defines to use to compile the shaders
  13569. * @param context defines the webGL context to use (if not set, the current one will be used)
  13570. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13571. * @returns the new webGL program
  13572. */
  13573. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13574. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13575. context = context || this._gl;
  13576. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13577. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13578. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13579. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13580. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13581. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13582. return program;
  13583. };
  13584. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13585. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13586. var shaderProgram = context.createProgram();
  13587. if (!shaderProgram) {
  13588. throw new Error("Unable to create program");
  13589. }
  13590. context.attachShader(shaderProgram, vertexShader);
  13591. context.attachShader(shaderProgram, fragmentShader);
  13592. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13593. var transformFeedback = this.createTransformFeedback();
  13594. this.bindTransformFeedback(transformFeedback);
  13595. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13596. shaderProgram.transformFeedback = transformFeedback;
  13597. }
  13598. context.linkProgram(shaderProgram);
  13599. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13600. this.bindTransformFeedback(null);
  13601. }
  13602. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13603. if (!linked) {
  13604. var error = context.getProgramInfoLog(shaderProgram);
  13605. if (error) {
  13606. throw new Error(error);
  13607. }
  13608. }
  13609. if (this.validateShaderPrograms) {
  13610. context.validateProgram(shaderProgram);
  13611. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13612. if (!validated) {
  13613. var error = context.getProgramInfoLog(shaderProgram);
  13614. if (error) {
  13615. throw new Error(error);
  13616. }
  13617. }
  13618. }
  13619. context.deleteShader(vertexShader);
  13620. context.deleteShader(fragmentShader);
  13621. return shaderProgram;
  13622. };
  13623. /**
  13624. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13625. * @param shaderProgram defines the webGL program to use
  13626. * @param uniformsNames defines the list of uniform names
  13627. * @returns an array of webGL uniform locations
  13628. */
  13629. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13630. var results = new Array();
  13631. for (var index = 0; index < uniformsNames.length; index++) {
  13632. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13633. }
  13634. return results;
  13635. };
  13636. /**
  13637. * Gets the lsit of active attributes for a given webGL program
  13638. * @param shaderProgram defines the webGL program to use
  13639. * @param attributesNames defines the list of attribute names to get
  13640. * @returns an array of indices indicating the offset of each attribute
  13641. */
  13642. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13643. var results = [];
  13644. for (var index = 0; index < attributesNames.length; index++) {
  13645. try {
  13646. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13647. }
  13648. catch (e) {
  13649. results.push(-1);
  13650. }
  13651. }
  13652. return results;
  13653. };
  13654. /**
  13655. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13656. * @param effect defines the effect to activate
  13657. */
  13658. Engine.prototype.enableEffect = function (effect) {
  13659. if (!effect) {
  13660. return;
  13661. }
  13662. // Use program
  13663. this.bindSamplers(effect);
  13664. this._currentEffect = effect;
  13665. if (effect.onBind) {
  13666. effect.onBind(effect);
  13667. }
  13668. effect.onBindObservable.notifyObservers(effect);
  13669. };
  13670. /**
  13671. * Set the value of an uniform to an array of int32
  13672. * @param uniform defines the webGL uniform location where to store the value
  13673. * @param array defines the array of int32 to store
  13674. */
  13675. Engine.prototype.setIntArray = function (uniform, array) {
  13676. if (!uniform)
  13677. return;
  13678. this._gl.uniform1iv(uniform, array);
  13679. };
  13680. /**
  13681. * Set the value of an uniform to an array of int32 (stored as vec2)
  13682. * @param uniform defines the webGL uniform location where to store the value
  13683. * @param array defines the array of int32 to store
  13684. */
  13685. Engine.prototype.setIntArray2 = function (uniform, array) {
  13686. if (!uniform || array.length % 2 !== 0)
  13687. return;
  13688. this._gl.uniform2iv(uniform, array);
  13689. };
  13690. /**
  13691. * Set the value of an uniform to an array of int32 (stored as vec3)
  13692. * @param uniform defines the webGL uniform location where to store the value
  13693. * @param array defines the array of int32 to store
  13694. */
  13695. Engine.prototype.setIntArray3 = function (uniform, array) {
  13696. if (!uniform || array.length % 3 !== 0)
  13697. return;
  13698. this._gl.uniform3iv(uniform, array);
  13699. };
  13700. /**
  13701. * Set the value of an uniform to an array of int32 (stored as vec4)
  13702. * @param uniform defines the webGL uniform location where to store the value
  13703. * @param array defines the array of int32 to store
  13704. */
  13705. Engine.prototype.setIntArray4 = function (uniform, array) {
  13706. if (!uniform || array.length % 4 !== 0)
  13707. return;
  13708. this._gl.uniform4iv(uniform, array);
  13709. };
  13710. /**
  13711. * Set the value of an uniform to an array of float32
  13712. * @param uniform defines the webGL uniform location where to store the value
  13713. * @param array defines the array of float32 to store
  13714. */
  13715. Engine.prototype.setFloatArray = function (uniform, array) {
  13716. if (!uniform)
  13717. return;
  13718. this._gl.uniform1fv(uniform, array);
  13719. };
  13720. /**
  13721. * Set the value of an uniform to an array of float32 (stored as vec2)
  13722. * @param uniform defines the webGL uniform location where to store the value
  13723. * @param array defines the array of float32 to store
  13724. */
  13725. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13726. if (!uniform || array.length % 2 !== 0)
  13727. return;
  13728. this._gl.uniform2fv(uniform, array);
  13729. };
  13730. /**
  13731. * Set the value of an uniform to an array of float32 (stored as vec3)
  13732. * @param uniform defines the webGL uniform location where to store the value
  13733. * @param array defines the array of float32 to store
  13734. */
  13735. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13736. if (!uniform || array.length % 3 !== 0)
  13737. return;
  13738. this._gl.uniform3fv(uniform, array);
  13739. };
  13740. /**
  13741. * Set the value of an uniform to an array of float32 (stored as vec4)
  13742. * @param uniform defines the webGL uniform location where to store the value
  13743. * @param array defines the array of float32 to store
  13744. */
  13745. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13746. if (!uniform || array.length % 4 !== 0)
  13747. return;
  13748. this._gl.uniform4fv(uniform, array);
  13749. };
  13750. /**
  13751. * Set the value of an uniform to an array of number
  13752. * @param uniform defines the webGL uniform location where to store the value
  13753. * @param array defines the array of number to store
  13754. */
  13755. Engine.prototype.setArray = function (uniform, array) {
  13756. if (!uniform)
  13757. return;
  13758. this._gl.uniform1fv(uniform, array);
  13759. };
  13760. /**
  13761. * Set the value of an uniform to an array of number (stored as vec2)
  13762. * @param uniform defines the webGL uniform location where to store the value
  13763. * @param array defines the array of number to store
  13764. */
  13765. Engine.prototype.setArray2 = function (uniform, array) {
  13766. if (!uniform || array.length % 2 !== 0)
  13767. return;
  13768. this._gl.uniform2fv(uniform, array);
  13769. };
  13770. /**
  13771. * Set the value of an uniform to an array of number (stored as vec3)
  13772. * @param uniform defines the webGL uniform location where to store the value
  13773. * @param array defines the array of number to store
  13774. */
  13775. Engine.prototype.setArray3 = function (uniform, array) {
  13776. if (!uniform || array.length % 3 !== 0)
  13777. return;
  13778. this._gl.uniform3fv(uniform, array);
  13779. };
  13780. /**
  13781. * Set the value of an uniform to an array of number (stored as vec4)
  13782. * @param uniform defines the webGL uniform location where to store the value
  13783. * @param array defines the array of number to store
  13784. */
  13785. Engine.prototype.setArray4 = function (uniform, array) {
  13786. if (!uniform || array.length % 4 !== 0)
  13787. return;
  13788. this._gl.uniform4fv(uniform, array);
  13789. };
  13790. /**
  13791. * Set the value of an uniform to an array of float32 (stored as matrices)
  13792. * @param uniform defines the webGL uniform location where to store the value
  13793. * @param matrices defines the array of float32 to store
  13794. */
  13795. Engine.prototype.setMatrices = function (uniform, matrices) {
  13796. if (!uniform)
  13797. return;
  13798. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13799. };
  13800. /**
  13801. * Set the value of an uniform to a matrix
  13802. * @param uniform defines the webGL uniform location where to store the value
  13803. * @param matrix defines the matrix to store
  13804. */
  13805. Engine.prototype.setMatrix = function (uniform, matrix) {
  13806. if (!uniform)
  13807. return;
  13808. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13809. };
  13810. /**
  13811. * Set the value of an uniform to a matrix (3x3)
  13812. * @param uniform defines the webGL uniform location where to store the value
  13813. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13814. */
  13815. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13816. if (!uniform)
  13817. return;
  13818. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13819. };
  13820. /**
  13821. * Set the value of an uniform to a matrix (2x2)
  13822. * @param uniform defines the webGL uniform location where to store the value
  13823. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13824. */
  13825. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13826. if (!uniform)
  13827. return;
  13828. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13829. };
  13830. /**
  13831. * Set the value of an uniform to a number (int)
  13832. * @param uniform defines the webGL uniform location where to store the value
  13833. * @param value defines the int number to store
  13834. */
  13835. Engine.prototype.setInt = function (uniform, value) {
  13836. if (!uniform)
  13837. return;
  13838. this._gl.uniform1i(uniform, value);
  13839. };
  13840. /**
  13841. * Set the value of an uniform to a number (float)
  13842. * @param uniform defines the webGL uniform location where to store the value
  13843. * @param value defines the float number to store
  13844. */
  13845. Engine.prototype.setFloat = function (uniform, value) {
  13846. if (!uniform)
  13847. return;
  13848. this._gl.uniform1f(uniform, value);
  13849. };
  13850. /**
  13851. * Set the value of an uniform to a vec2
  13852. * @param uniform defines the webGL uniform location where to store the value
  13853. * @param x defines the 1st component of the value
  13854. * @param y defines the 2nd component of the value
  13855. */
  13856. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13857. if (!uniform)
  13858. return;
  13859. this._gl.uniform2f(uniform, x, y);
  13860. };
  13861. /**
  13862. * Set the value of an uniform to a vec3
  13863. * @param uniform defines the webGL uniform location where to store the value
  13864. * @param x defines the 1st component of the value
  13865. * @param y defines the 2nd component of the value
  13866. * @param z defines the 3rd component of the value
  13867. */
  13868. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13869. if (!uniform)
  13870. return;
  13871. this._gl.uniform3f(uniform, x, y, z);
  13872. };
  13873. /**
  13874. * Set the value of an uniform to a boolean
  13875. * @param uniform defines the webGL uniform location where to store the value
  13876. * @param bool defines the boolean to store
  13877. */
  13878. Engine.prototype.setBool = function (uniform, bool) {
  13879. if (!uniform)
  13880. return;
  13881. this._gl.uniform1i(uniform, bool);
  13882. };
  13883. /**
  13884. * Set the value of an uniform to a vec4
  13885. * @param uniform defines the webGL uniform location where to store the value
  13886. * @param x defines the 1st component of the value
  13887. * @param y defines the 2nd component of the value
  13888. * @param z defines the 3rd component of the value
  13889. * @param w defines the 4th component of the value
  13890. */
  13891. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13892. if (!uniform)
  13893. return;
  13894. this._gl.uniform4f(uniform, x, y, z, w);
  13895. };
  13896. /**
  13897. * Set the value of an uniform to a Color3
  13898. * @param uniform defines the webGL uniform location where to store the value
  13899. * @param color3 defines the color to store
  13900. */
  13901. Engine.prototype.setColor3 = function (uniform, color3) {
  13902. if (!uniform)
  13903. return;
  13904. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  13905. };
  13906. /**
  13907. * Set the value of an uniform to a Color3 and an alpha value
  13908. * @param uniform defines the webGL uniform location where to store the value
  13909. * @param color3 defines the color to store
  13910. * @param alpha defines the alpha component to store
  13911. */
  13912. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  13913. if (!uniform)
  13914. return;
  13915. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  13916. };
  13917. /**
  13918. * Sets a Color4 on a uniform variable
  13919. * @param uniform defines the uniform location
  13920. * @param color4 defines the value to be set
  13921. */
  13922. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  13923. if (!uniform)
  13924. return;
  13925. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  13926. };
  13927. // States
  13928. /**
  13929. * Set various states to the webGL context
  13930. * @param culling defines backface culling state
  13931. * @param zOffset defines the value to apply to zOffset (0 by default)
  13932. * @param force defines if states must be applied even if cache is up to date
  13933. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  13934. */
  13935. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  13936. if (zOffset === void 0) { zOffset = 0; }
  13937. if (reverseSide === void 0) { reverseSide = false; }
  13938. // Culling
  13939. if (this._depthCullingState.cull !== culling || force) {
  13940. this._depthCullingState.cull = culling;
  13941. }
  13942. // Cull face
  13943. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  13944. if (this._depthCullingState.cullFace !== cullFace || force) {
  13945. this._depthCullingState.cullFace = cullFace;
  13946. }
  13947. // Z offset
  13948. this.setZOffset(zOffset);
  13949. // Front face
  13950. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  13951. if (this._depthCullingState.frontFace !== frontFace || force) {
  13952. this._depthCullingState.frontFace = frontFace;
  13953. }
  13954. };
  13955. /**
  13956. * Set the z offset to apply to current rendering
  13957. * @param value defines the offset to apply
  13958. */
  13959. Engine.prototype.setZOffset = function (value) {
  13960. this._depthCullingState.zOffset = value;
  13961. };
  13962. /**
  13963. * Gets the current value of the zOffset
  13964. * @returns the current zOffset state
  13965. */
  13966. Engine.prototype.getZOffset = function () {
  13967. return this._depthCullingState.zOffset;
  13968. };
  13969. /**
  13970. * Enable or disable depth buffering
  13971. * @param enable defines the state to set
  13972. */
  13973. Engine.prototype.setDepthBuffer = function (enable) {
  13974. this._depthCullingState.depthTest = enable;
  13975. };
  13976. /**
  13977. * Gets a boolean indicating if depth writing is enabled
  13978. * @returns the current depth writing state
  13979. */
  13980. Engine.prototype.getDepthWrite = function () {
  13981. return this._depthCullingState.depthMask;
  13982. };
  13983. /**
  13984. * Enable or disable depth writing
  13985. * @param enable defines the state to set
  13986. */
  13987. Engine.prototype.setDepthWrite = function (enable) {
  13988. this._depthCullingState.depthMask = enable;
  13989. };
  13990. /**
  13991. * Enable or disable color writing
  13992. * @param enable defines the state to set
  13993. */
  13994. Engine.prototype.setColorWrite = function (enable) {
  13995. this._gl.colorMask(enable, enable, enable, enable);
  13996. this._colorWrite = enable;
  13997. };
  13998. /**
  13999. * Gets a boolean indicating if color writing is enabled
  14000. * @returns the current color writing state
  14001. */
  14002. Engine.prototype.getColorWrite = function () {
  14003. return this._colorWrite;
  14004. };
  14005. /**
  14006. * Sets alpha constants used by some alpha blending modes
  14007. * @param r defines the red component
  14008. * @param g defines the green component
  14009. * @param b defines the blue component
  14010. * @param a defines the alpha component
  14011. */
  14012. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14013. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14014. };
  14015. /**
  14016. * Sets the current alpha mode
  14017. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14018. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14019. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14020. */
  14021. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14022. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14023. if (this._alphaMode === mode) {
  14024. return;
  14025. }
  14026. switch (mode) {
  14027. case Engine.ALPHA_DISABLE:
  14028. this._alphaState.alphaBlend = false;
  14029. break;
  14030. case Engine.ALPHA_PREMULTIPLIED:
  14031. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14032. this._alphaState.alphaBlend = true;
  14033. break;
  14034. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14035. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14036. this._alphaState.alphaBlend = true;
  14037. break;
  14038. case Engine.ALPHA_COMBINE:
  14039. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14040. this._alphaState.alphaBlend = true;
  14041. break;
  14042. case Engine.ALPHA_ONEONE:
  14043. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14044. this._alphaState.alphaBlend = true;
  14045. break;
  14046. case Engine.ALPHA_ADD:
  14047. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14048. this._alphaState.alphaBlend = true;
  14049. break;
  14050. case Engine.ALPHA_SUBTRACT:
  14051. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14052. this._alphaState.alphaBlend = true;
  14053. break;
  14054. case Engine.ALPHA_MULTIPLY:
  14055. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14056. this._alphaState.alphaBlend = true;
  14057. break;
  14058. case Engine.ALPHA_MAXIMIZED:
  14059. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14060. this._alphaState.alphaBlend = true;
  14061. break;
  14062. case Engine.ALPHA_INTERPOLATE:
  14063. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14064. this._alphaState.alphaBlend = true;
  14065. break;
  14066. case Engine.ALPHA_SCREENMODE:
  14067. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14068. this._alphaState.alphaBlend = true;
  14069. break;
  14070. }
  14071. if (!noDepthWriteChange) {
  14072. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14073. }
  14074. this._alphaMode = mode;
  14075. };
  14076. /**
  14077. * Gets the current alpha mode
  14078. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14079. * @returns the current alpha mode
  14080. */
  14081. Engine.prototype.getAlphaMode = function () {
  14082. return this._alphaMode;
  14083. };
  14084. // Textures
  14085. /**
  14086. * Clears the list of texture accessible through engine.
  14087. * This can help preventing texture load conflict due to name collision.
  14088. */
  14089. Engine.prototype.clearInternalTexturesCache = function () {
  14090. this._internalTexturesCache = [];
  14091. };
  14092. /**
  14093. * Force the entire cache to be cleared
  14094. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14095. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14096. */
  14097. Engine.prototype.wipeCaches = function (bruteForce) {
  14098. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14099. return;
  14100. }
  14101. this._currentEffect = null;
  14102. this._unpackFlipYCached = null;
  14103. this._viewportCached.x = 0;
  14104. this._viewportCached.y = 0;
  14105. this._viewportCached.z = 0;
  14106. this._viewportCached.w = 0;
  14107. if (bruteForce) {
  14108. this.resetTextureCache();
  14109. this._currentProgram = null;
  14110. this._stencilState.reset();
  14111. this._depthCullingState.reset();
  14112. this.setDepthFunctionToLessOrEqual();
  14113. this._alphaState.reset();
  14114. }
  14115. this._resetVertexBufferBinding();
  14116. this._cachedIndexBuffer = null;
  14117. this._cachedEffectForVertexBuffers = null;
  14118. this._unbindVertexArrayObject();
  14119. this.bindIndexBuffer(null);
  14120. };
  14121. /**
  14122. * Set the compressed texture format to use, based on the formats you have, and the formats
  14123. * supported by the hardware / browser.
  14124. *
  14125. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14126. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14127. * to API arguments needed to compressed textures. This puts the burden on the container
  14128. * generator to house the arcane code for determining these for current & future formats.
  14129. *
  14130. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14131. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14132. *
  14133. * Note: The result of this call is not taken into account when a texture is base64.
  14134. *
  14135. * @param formatsAvailable defines the list of those format families you have created
  14136. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14137. *
  14138. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14139. * @returns The extension selected.
  14140. */
  14141. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14142. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14143. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14144. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14145. return this._textureFormatInUse = this._texturesSupported[i];
  14146. }
  14147. }
  14148. }
  14149. // actively set format to nothing, to allow this to be called more than once
  14150. // and possibly fail the 2nd time
  14151. this._textureFormatInUse = null;
  14152. return null;
  14153. };
  14154. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14155. var gl = this._gl;
  14156. var magFilter = gl.NEAREST;
  14157. var minFilter = gl.NEAREST;
  14158. switch (samplingMode) {
  14159. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14160. magFilter = gl.LINEAR;
  14161. if (generateMipMaps) {
  14162. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14163. }
  14164. else {
  14165. minFilter = gl.LINEAR;
  14166. }
  14167. break;
  14168. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14169. magFilter = gl.LINEAR;
  14170. if (generateMipMaps) {
  14171. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14172. }
  14173. else {
  14174. minFilter = gl.LINEAR;
  14175. }
  14176. break;
  14177. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14178. magFilter = gl.NEAREST;
  14179. if (generateMipMaps) {
  14180. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14181. }
  14182. else {
  14183. minFilter = gl.NEAREST;
  14184. }
  14185. break;
  14186. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14187. magFilter = gl.NEAREST;
  14188. if (generateMipMaps) {
  14189. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14190. }
  14191. else {
  14192. minFilter = gl.NEAREST;
  14193. }
  14194. break;
  14195. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14196. magFilter = gl.NEAREST;
  14197. if (generateMipMaps) {
  14198. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14199. }
  14200. else {
  14201. minFilter = gl.LINEAR;
  14202. }
  14203. break;
  14204. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14205. magFilter = gl.NEAREST;
  14206. if (generateMipMaps) {
  14207. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14208. }
  14209. else {
  14210. minFilter = gl.LINEAR;
  14211. }
  14212. break;
  14213. case Engine.TEXTURE_NEAREST_LINEAR:
  14214. magFilter = gl.NEAREST;
  14215. minFilter = gl.LINEAR;
  14216. break;
  14217. case Engine.TEXTURE_NEAREST_NEAREST:
  14218. magFilter = gl.NEAREST;
  14219. minFilter = gl.NEAREST;
  14220. break;
  14221. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14222. magFilter = gl.LINEAR;
  14223. if (generateMipMaps) {
  14224. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14225. }
  14226. else {
  14227. minFilter = gl.NEAREST;
  14228. }
  14229. break;
  14230. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14231. magFilter = gl.LINEAR;
  14232. if (generateMipMaps) {
  14233. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14234. }
  14235. else {
  14236. minFilter = gl.NEAREST;
  14237. }
  14238. break;
  14239. case Engine.TEXTURE_LINEAR_LINEAR:
  14240. magFilter = gl.LINEAR;
  14241. minFilter = gl.LINEAR;
  14242. break;
  14243. case Engine.TEXTURE_LINEAR_NEAREST:
  14244. magFilter = gl.LINEAR;
  14245. minFilter = gl.NEAREST;
  14246. break;
  14247. }
  14248. return {
  14249. min: minFilter,
  14250. mag: magFilter
  14251. };
  14252. };
  14253. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14254. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14255. var img;
  14256. var onload = function () {
  14257. loadedImages[index] = img;
  14258. loadedImages._internalCount++;
  14259. if (scene) {
  14260. scene._removePendingData(img);
  14261. }
  14262. if (loadedImages._internalCount === 6) {
  14263. onfinish(loadedImages);
  14264. }
  14265. };
  14266. var onerror = function (message, exception) {
  14267. if (scene) {
  14268. scene._removePendingData(img);
  14269. }
  14270. if (onErrorCallBack) {
  14271. onErrorCallBack(message, exception);
  14272. }
  14273. };
  14274. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14275. if (scene) {
  14276. scene._addPendingData(img);
  14277. }
  14278. };
  14279. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14280. if (onError === void 0) { onError = null; }
  14281. var loadedImages = [];
  14282. loadedImages._internalCount = 0;
  14283. for (var index = 0; index < 6; index++) {
  14284. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14285. }
  14286. };
  14287. ;
  14288. /** @hidden */
  14289. Engine.prototype._createTexture = function () {
  14290. var texture = this._gl.createTexture();
  14291. if (!texture) {
  14292. throw new Error("Unable to create texture");
  14293. }
  14294. return texture;
  14295. };
  14296. /**
  14297. * Usually called from BABYLON.Texture.ts.
  14298. * Passed information to create a WebGLTexture
  14299. * @param urlArg defines a value which contains one of the following:
  14300. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14301. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14302. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14303. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14304. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14305. * @param scene needed for loading to the correct scene
  14306. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14307. * @param onLoad optional callback to be called upon successful completion
  14308. * @param onError optional callback to be called upon failure
  14309. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14310. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14311. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14312. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14313. */
  14314. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14315. var _this = this;
  14316. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14317. if (onLoad === void 0) { onLoad = null; }
  14318. if (onError === void 0) { onError = null; }
  14319. if (buffer === void 0) { buffer = null; }
  14320. if (fallback === void 0) { fallback = null; }
  14321. if (format === void 0) { format = null; }
  14322. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14323. var fromData = url.substr(0, 5) === "data:";
  14324. var fromBlob = url.substr(0, 5) === "blob:";
  14325. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14326. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14327. // establish the file extension, if possible
  14328. var lastDot = url.lastIndexOf('.');
  14329. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14330. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14331. var isTGA = (extension.indexOf(".tga") === 0);
  14332. // determine if a ktx file should be substituted
  14333. var isKTX = false;
  14334. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14335. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14336. isKTX = true;
  14337. }
  14338. if (scene) {
  14339. scene._addPendingData(texture);
  14340. }
  14341. texture.url = url;
  14342. texture.generateMipMaps = !noMipmap;
  14343. texture.samplingMode = samplingMode;
  14344. texture.invertY = invertY;
  14345. if (!this._doNotHandleContextLost) {
  14346. // Keep a link to the buffer only if we plan to handle context lost
  14347. texture._buffer = buffer;
  14348. }
  14349. var onLoadObserver = null;
  14350. if (onLoad && !fallback) {
  14351. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14352. }
  14353. if (!fallback)
  14354. this._internalTexturesCache.push(texture);
  14355. var onerror = function (message, exception) {
  14356. if (scene) {
  14357. scene._removePendingData(texture);
  14358. }
  14359. if (onLoadObserver && !isKTX) {
  14360. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14361. texture.onLoadedObservable.remove(onLoadObserver);
  14362. }
  14363. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14364. if (isKTX) {
  14365. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14366. }
  14367. else if (BABYLON.Tools.UseFallbackTexture) {
  14368. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14369. }
  14370. if (onError) {
  14371. onError(message || "Unknown error", exception);
  14372. }
  14373. };
  14374. var callback = null;
  14375. // processing for non-image formats
  14376. if (isKTX || isTGA || isDDS) {
  14377. if (isKTX) {
  14378. callback = function (data) {
  14379. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14380. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14381. ktx.uploadLevels(texture, !noMipmap);
  14382. return false;
  14383. }, samplingMode);
  14384. };
  14385. }
  14386. else if (isTGA) {
  14387. callback = function (arrayBuffer) {
  14388. var data = new Uint8Array(arrayBuffer);
  14389. var header = BABYLON.TGATools.GetTGAHeader(data);
  14390. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14391. BABYLON.TGATools.UploadContent(texture, data);
  14392. return false;
  14393. }, samplingMode);
  14394. };
  14395. }
  14396. else if (isDDS) {
  14397. callback = function (data) {
  14398. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14399. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14400. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14401. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, loadMipmap, 1);
  14402. return false;
  14403. }, samplingMode);
  14404. };
  14405. }
  14406. if (!buffer) {
  14407. this._loadFile(url, function (data) {
  14408. if (callback) {
  14409. callback(data);
  14410. }
  14411. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14412. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14413. });
  14414. }
  14415. else {
  14416. if (callback) {
  14417. callback(buffer);
  14418. }
  14419. }
  14420. // image format processing
  14421. }
  14422. else {
  14423. var onload = function (img) {
  14424. if (fromBlob && !_this._doNotHandleContextLost) {
  14425. // We need to store the image if we need to rebuild the texture
  14426. // in case of a webgl context lost
  14427. texture._buffer = img;
  14428. }
  14429. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14430. var gl = _this._gl;
  14431. var isPot = (img.width === potWidth && img.height === potHeight);
  14432. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14433. if (isPot) {
  14434. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14435. return false;
  14436. }
  14437. var maxTextureSize = _this._caps.maxTextureSize;
  14438. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14439. _this._prepareWorkingCanvas();
  14440. if (!_this._workingCanvas || !_this._workingContext) {
  14441. return false;
  14442. }
  14443. _this._workingCanvas.width = potWidth;
  14444. _this._workingCanvas.height = potHeight;
  14445. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14446. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14447. texture.width = potWidth;
  14448. texture.height = potHeight;
  14449. return false;
  14450. }
  14451. else {
  14452. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14453. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14454. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14455. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14456. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14457. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14458. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14459. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14460. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14461. _this._releaseTexture(source_1);
  14462. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14463. continuationCallback();
  14464. });
  14465. }
  14466. return true;
  14467. }, samplingMode);
  14468. };
  14469. if (!fromData || isBase64) {
  14470. if (buffer instanceof HTMLImageElement) {
  14471. onload(buffer);
  14472. }
  14473. else {
  14474. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14475. }
  14476. }
  14477. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14478. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14479. }
  14480. else {
  14481. onload(buffer);
  14482. }
  14483. }
  14484. return texture;
  14485. };
  14486. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14487. var _this = this;
  14488. var rtt = this.createRenderTargetTexture({
  14489. width: destination.width,
  14490. height: destination.height,
  14491. }, {
  14492. generateMipMaps: false,
  14493. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14494. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14495. generateDepthBuffer: false,
  14496. generateStencilBuffer: false
  14497. });
  14498. if (!this._rescalePostProcess) {
  14499. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14500. }
  14501. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14502. _this._rescalePostProcess.onApply = function (effect) {
  14503. effect._bindTexture("textureSampler", source);
  14504. };
  14505. var hostingScene = scene;
  14506. if (!hostingScene) {
  14507. hostingScene = _this.scenes[_this.scenes.length - 1];
  14508. }
  14509. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14510. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14511. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14512. _this.unBindFramebuffer(rtt);
  14513. _this._releaseTexture(rtt);
  14514. if (onComplete) {
  14515. onComplete();
  14516. }
  14517. });
  14518. };
  14519. /**
  14520. * Update a raw texture
  14521. * @param texture defines the texture to update
  14522. * @param data defines the data to store in the texture
  14523. * @param format defines the format of the data
  14524. * @param invertY defines if data must be stored with Y axis inverted
  14525. * @param compression defines the compression used (null by default)
  14526. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14527. */
  14528. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14529. if (compression === void 0) { compression = null; }
  14530. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14531. if (!texture) {
  14532. return;
  14533. }
  14534. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14535. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14536. // babylon's internalFormat but gl's texImage2D format
  14537. var internalFormat = this._getInternalFormat(format);
  14538. var textureType = this._getWebGLTextureType(type);
  14539. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14540. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14541. if (!this._doNotHandleContextLost) {
  14542. texture._bufferView = data;
  14543. texture.format = format;
  14544. texture.type = type;
  14545. texture.invertY = invertY;
  14546. texture._compression = compression;
  14547. }
  14548. if (texture.width % 4 !== 0) {
  14549. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14550. }
  14551. if (compression && data) {
  14552. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14553. }
  14554. else {
  14555. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14556. }
  14557. if (texture.generateMipMaps) {
  14558. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14559. }
  14560. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14561. // this.resetTextureCache();
  14562. texture.isReady = true;
  14563. };
  14564. /**
  14565. * Creates a raw texture
  14566. * @param data defines the data to store in the texture
  14567. * @param width defines the width of the texture
  14568. * @param height defines the height of the texture
  14569. * @param format defines the format of the data
  14570. * @param generateMipMaps defines if the engine should generate the mip levels
  14571. * @param invertY defines if data must be stored with Y axis inverted
  14572. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14573. * @param compression defines the compression used (null by default)
  14574. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14575. * @returns the raw texture inside an InternalTexture
  14576. */
  14577. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14578. if (compression === void 0) { compression = null; }
  14579. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14580. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14581. texture.baseWidth = width;
  14582. texture.baseHeight = height;
  14583. texture.width = width;
  14584. texture.height = height;
  14585. texture.format = format;
  14586. texture.generateMipMaps = generateMipMaps;
  14587. texture.samplingMode = samplingMode;
  14588. texture.invertY = invertY;
  14589. texture._compression = compression;
  14590. texture.type = type;
  14591. if (!this._doNotHandleContextLost) {
  14592. texture._bufferView = data;
  14593. }
  14594. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14595. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14596. // Filters
  14597. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14598. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14599. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14600. if (generateMipMaps) {
  14601. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14602. }
  14603. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14604. this._internalTexturesCache.push(texture);
  14605. return texture;
  14606. };
  14607. /** @hidden */
  14608. Engine.prototype._unpackFlipY = function (value) {
  14609. if (this._unpackFlipYCached !== value) {
  14610. this._unpackFlipYCached = value;
  14611. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14612. }
  14613. };
  14614. /** @hidden */
  14615. Engine.prototype._getUnpackAlignement = function () {
  14616. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14617. };
  14618. /**
  14619. * Creates a dynamic texture
  14620. * @param width defines the width of the texture
  14621. * @param height defines the height of the texture
  14622. * @param generateMipMaps defines if the engine should generate the mip levels
  14623. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14624. * @returns the dynamic texture inside an InternalTexture
  14625. */
  14626. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14627. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14628. texture.baseWidth = width;
  14629. texture.baseHeight = height;
  14630. if (generateMipMaps) {
  14631. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14632. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14633. }
  14634. // this.resetTextureCache();
  14635. texture.width = width;
  14636. texture.height = height;
  14637. texture.isReady = false;
  14638. texture.generateMipMaps = generateMipMaps;
  14639. texture.samplingMode = samplingMode;
  14640. this.updateTextureSamplingMode(samplingMode, texture);
  14641. this._internalTexturesCache.push(texture);
  14642. return texture;
  14643. };
  14644. /**
  14645. * Update the sampling mode of a given texture
  14646. * @param samplingMode defines the required sampling mode
  14647. * @param texture defines the texture to update
  14648. */
  14649. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14650. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14651. if (texture.isCube) {
  14652. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14653. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14654. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14655. }
  14656. else if (texture.is3D) {
  14657. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14658. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14659. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14660. }
  14661. else {
  14662. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14663. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14664. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14665. }
  14666. texture.samplingMode = samplingMode;
  14667. };
  14668. /**
  14669. * Update the content of a dynamic texture
  14670. * @param texture defines the texture to update
  14671. * @param canvas defines the canvas containing the source
  14672. * @param invertY defines if data must be stored with Y axis inverted
  14673. * @param premulAlpha defines if alpha is stored as premultiplied
  14674. * @param format defines the format of the data
  14675. */
  14676. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14677. if (premulAlpha === void 0) { premulAlpha = false; }
  14678. if (!texture) {
  14679. return;
  14680. }
  14681. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14682. this._unpackFlipY(invertY);
  14683. if (premulAlpha) {
  14684. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14685. }
  14686. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14687. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14688. if (texture.generateMipMaps) {
  14689. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14690. }
  14691. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14692. if (premulAlpha) {
  14693. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14694. }
  14695. texture.isReady = true;
  14696. };
  14697. /**
  14698. * Update a video texture
  14699. * @param texture defines the texture to update
  14700. * @param video defines the video element to use
  14701. * @param invertY defines if data must be stored with Y axis inverted
  14702. */
  14703. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14704. if (!texture || texture._isDisabled) {
  14705. return;
  14706. }
  14707. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14708. this._unpackFlipY(!invertY); // Video are upside down by default
  14709. try {
  14710. // Testing video texture support
  14711. if (this._videoTextureSupported === undefined) {
  14712. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14713. if (this._gl.getError() !== 0) {
  14714. this._videoTextureSupported = false;
  14715. }
  14716. else {
  14717. this._videoTextureSupported = true;
  14718. }
  14719. }
  14720. // Copy video through the current working canvas if video texture is not supported
  14721. if (!this._videoTextureSupported) {
  14722. if (!texture._workingCanvas) {
  14723. texture._workingCanvas = document.createElement("canvas");
  14724. var context = texture._workingCanvas.getContext("2d");
  14725. if (!context) {
  14726. throw new Error("Unable to get 2d context");
  14727. }
  14728. texture._workingContext = context;
  14729. texture._workingCanvas.width = texture.width;
  14730. texture._workingCanvas.height = texture.height;
  14731. }
  14732. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14733. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14734. }
  14735. else {
  14736. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14737. }
  14738. if (texture.generateMipMaps) {
  14739. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14740. }
  14741. if (!wasPreviouslyBound) {
  14742. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14743. }
  14744. // this.resetTextureCache();
  14745. texture.isReady = true;
  14746. }
  14747. catch (ex) {
  14748. // Something unexpected
  14749. // Let's disable the texture
  14750. texture._isDisabled = true;
  14751. }
  14752. };
  14753. /**
  14754. * Updates a depth texture Comparison Mode and Function.
  14755. * If the comparison Function is equal to 0, the mode will be set to none.
  14756. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14757. * @param texture The texture to set the comparison function for
  14758. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14759. */
  14760. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14761. if (this.webGLVersion === 1) {
  14762. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14763. return;
  14764. }
  14765. var gl = this._gl;
  14766. if (texture.isCube) {
  14767. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14768. if (comparisonFunction === 0) {
  14769. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14770. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14771. }
  14772. else {
  14773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14774. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14775. }
  14776. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14777. }
  14778. else {
  14779. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14780. if (comparisonFunction === 0) {
  14781. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14782. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14783. }
  14784. else {
  14785. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14786. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14787. }
  14788. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14789. }
  14790. texture._comparisonFunction = comparisonFunction;
  14791. };
  14792. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14793. var width = size.width || size;
  14794. var height = size.height || size;
  14795. internalTexture.baseWidth = width;
  14796. internalTexture.baseHeight = height;
  14797. internalTexture.width = width;
  14798. internalTexture.height = height;
  14799. internalTexture.isReady = true;
  14800. internalTexture.samples = 1;
  14801. internalTexture.generateMipMaps = false;
  14802. internalTexture._generateDepthBuffer = true;
  14803. internalTexture._generateStencilBuffer = generateStencil;
  14804. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14805. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14806. internalTexture._comparisonFunction = comparisonFunction;
  14807. var gl = this._gl;
  14808. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14809. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14810. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14811. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14812. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14813. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14814. if (comparisonFunction === 0) {
  14815. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14816. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14817. }
  14818. else {
  14819. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14820. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14821. }
  14822. };
  14823. /**
  14824. * Creates a depth stencil texture.
  14825. * This is only available in WebGL 2 or with the depth texture extension available.
  14826. * @param size The size of face edge in the texture.
  14827. * @param options The options defining the texture.
  14828. * @returns The texture
  14829. */
  14830. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14831. if (options.isCube) {
  14832. var width = size.width || size;
  14833. return this._createDepthStencilCubeTexture(width, options);
  14834. }
  14835. else {
  14836. return this._createDepthStencilTexture(size, options);
  14837. }
  14838. };
  14839. /**
  14840. * Creates a depth stencil texture.
  14841. * This is only available in WebGL 2 or with the depth texture extension available.
  14842. * @param size The size of face edge in the texture.
  14843. * @param options The options defining the texture.
  14844. * @returns The texture
  14845. */
  14846. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14847. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14848. if (!this._caps.depthTextureExtension) {
  14849. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14850. return internalTexture;
  14851. }
  14852. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14853. var gl = this._gl;
  14854. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14855. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14856. if (this.webGLVersion > 1) {
  14857. if (internalOptions.generateStencil) {
  14858. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14859. }
  14860. else {
  14861. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14862. }
  14863. }
  14864. else {
  14865. if (internalOptions.generateStencil) {
  14866. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14867. }
  14868. else {
  14869. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14870. }
  14871. }
  14872. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14873. return internalTexture;
  14874. };
  14875. /**
  14876. * Creates a depth stencil cube texture.
  14877. * This is only available in WebGL 2.
  14878. * @param size The size of face edge in the cube texture.
  14879. * @param options The options defining the cube texture.
  14880. * @returns The cube texture
  14881. */
  14882. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14883. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14884. internalTexture.isCube = true;
  14885. if (this.webGLVersion === 1) {
  14886. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14887. return internalTexture;
  14888. }
  14889. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14890. var gl = this._gl;
  14891. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14892. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14893. // Create the depth/stencil buffer
  14894. for (var face = 0; face < 6; face++) {
  14895. if (internalOptions.generateStencil) {
  14896. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14897. }
  14898. else {
  14899. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14900. }
  14901. }
  14902. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14903. return internalTexture;
  14904. };
  14905. /**
  14906. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14907. * @param renderTarget The render target to set the frame buffer for
  14908. */
  14909. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14910. // Create the framebuffer
  14911. var internalTexture = renderTarget.getInternalTexture();
  14912. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14913. return;
  14914. }
  14915. var gl = this._gl;
  14916. var depthStencilTexture = renderTarget.depthStencilTexture;
  14917. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14918. if (depthStencilTexture.isCube) {
  14919. if (depthStencilTexture._generateStencilBuffer) {
  14920. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14921. }
  14922. else {
  14923. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14924. }
  14925. }
  14926. else {
  14927. if (depthStencilTexture._generateStencilBuffer) {
  14928. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14929. }
  14930. else {
  14931. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14932. }
  14933. }
  14934. this.bindUnboundFramebuffer(null);
  14935. };
  14936. /**
  14937. * Creates a new render target texture
  14938. * @param size defines the size of the texture
  14939. * @param options defines the options used to create the texture
  14940. * @returns a new render target texture stored in an InternalTexture
  14941. */
  14942. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14943. var fullOptions = new RenderTargetCreationOptions();
  14944. if (options !== undefined && typeof options === "object") {
  14945. fullOptions.generateMipMaps = options.generateMipMaps;
  14946. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14947. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14948. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14949. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14950. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14951. }
  14952. else {
  14953. fullOptions.generateMipMaps = options;
  14954. fullOptions.generateDepthBuffer = true;
  14955. fullOptions.generateStencilBuffer = false;
  14956. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14957. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  14958. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14959. }
  14960. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14961. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14962. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14963. }
  14964. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14965. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14966. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14967. }
  14968. var gl = this._gl;
  14969. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14970. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14971. var width = size.width || size;
  14972. var height = size.height || size;
  14973. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  14974. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14975. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14976. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14977. }
  14978. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14979. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14980. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14981. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14982. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  14983. // Create the framebuffer
  14984. var currentFrameBuffer = this._currentFramebuffer;
  14985. var framebuffer = gl.createFramebuffer();
  14986. this.bindUnboundFramebuffer(framebuffer);
  14987. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14988. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  14989. if (fullOptions.generateMipMaps) {
  14990. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14991. }
  14992. // Unbind
  14993. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14994. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14995. this.bindUnboundFramebuffer(currentFrameBuffer);
  14996. texture._framebuffer = framebuffer;
  14997. texture.baseWidth = width;
  14998. texture.baseHeight = height;
  14999. texture.width = width;
  15000. texture.height = height;
  15001. texture.isReady = true;
  15002. texture.samples = 1;
  15003. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15004. texture.samplingMode = fullOptions.samplingMode;
  15005. texture.type = fullOptions.type;
  15006. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15007. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15008. // this.resetTextureCache();
  15009. this._internalTexturesCache.push(texture);
  15010. return texture;
  15011. };
  15012. /**
  15013. * Create a multi render target texture
  15014. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15015. * @param size defines the size of the texture
  15016. * @param options defines the creation options
  15017. * @returns the cube texture as an InternalTexture
  15018. */
  15019. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15020. var generateMipMaps = false;
  15021. var generateDepthBuffer = true;
  15022. var generateStencilBuffer = false;
  15023. var generateDepthTexture = false;
  15024. var textureCount = 1;
  15025. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15026. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15027. var types = new Array();
  15028. var samplingModes = new Array();
  15029. if (options !== undefined) {
  15030. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15031. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15032. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15033. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15034. textureCount = options.textureCount || 1;
  15035. if (options.types) {
  15036. types = options.types;
  15037. }
  15038. if (options.samplingModes) {
  15039. samplingModes = options.samplingModes;
  15040. }
  15041. }
  15042. var gl = this._gl;
  15043. // Create the framebuffer
  15044. var framebuffer = gl.createFramebuffer();
  15045. this.bindUnboundFramebuffer(framebuffer);
  15046. var width = size.width || size;
  15047. var height = size.height || size;
  15048. var textures = [];
  15049. var attachments = [];
  15050. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15051. for (var i = 0; i < textureCount; i++) {
  15052. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15053. var type = types[i] || defaultType;
  15054. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15055. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15056. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15057. }
  15058. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15059. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15060. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15061. }
  15062. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15063. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15064. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15065. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15066. }
  15067. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15068. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15069. textures.push(texture);
  15070. attachments.push(attachment);
  15071. gl.activeTexture(gl["TEXTURE" + i]);
  15072. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15073. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15074. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15075. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15076. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15077. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15078. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15079. if (generateMipMaps) {
  15080. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15081. }
  15082. // Unbind
  15083. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15084. texture._framebuffer = framebuffer;
  15085. texture._depthStencilBuffer = depthStencilBuffer;
  15086. texture.baseWidth = width;
  15087. texture.baseHeight = height;
  15088. texture.width = width;
  15089. texture.height = height;
  15090. texture.isReady = true;
  15091. texture.samples = 1;
  15092. texture.generateMipMaps = generateMipMaps;
  15093. texture.samplingMode = samplingMode;
  15094. texture.type = type;
  15095. texture._generateDepthBuffer = generateDepthBuffer;
  15096. texture._generateStencilBuffer = generateStencilBuffer;
  15097. texture._attachments = attachments;
  15098. this._internalTexturesCache.push(texture);
  15099. }
  15100. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15101. // Depth texture
  15102. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15103. gl.activeTexture(gl.TEXTURE0);
  15104. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15105. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15106. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15107. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15108. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15109. gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  15110. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15111. depthTexture._framebuffer = framebuffer;
  15112. depthTexture.baseWidth = width;
  15113. depthTexture.baseHeight = height;
  15114. depthTexture.width = width;
  15115. depthTexture.height = height;
  15116. depthTexture.isReady = true;
  15117. depthTexture.samples = 1;
  15118. depthTexture.generateMipMaps = generateMipMaps;
  15119. depthTexture.samplingMode = gl.NEAREST;
  15120. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15121. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15122. textures.push(depthTexture);
  15123. this._internalTexturesCache.push(depthTexture);
  15124. }
  15125. gl.drawBuffers(attachments);
  15126. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15127. this.bindUnboundFramebuffer(null);
  15128. this.resetTextureCache();
  15129. return textures;
  15130. };
  15131. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15132. if (samples === void 0) { samples = 1; }
  15133. var depthStencilBuffer = null;
  15134. var gl = this._gl;
  15135. // Create the depth/stencil buffer
  15136. if (generateStencilBuffer) {
  15137. depthStencilBuffer = gl.createRenderbuffer();
  15138. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15139. if (samples > 1) {
  15140. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15141. }
  15142. else {
  15143. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15144. }
  15145. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15146. }
  15147. else if (generateDepthBuffer) {
  15148. depthStencilBuffer = gl.createRenderbuffer();
  15149. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15150. if (samples > 1) {
  15151. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15152. }
  15153. else {
  15154. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15155. }
  15156. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15157. }
  15158. return depthStencilBuffer;
  15159. };
  15160. /**
  15161. * Updates the sample count of a render target texture
  15162. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15163. * @param texture defines the texture to update
  15164. * @param samples defines the sample count to set
  15165. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15166. */
  15167. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15168. if (this.webGLVersion < 2 || !texture) {
  15169. return 1;
  15170. }
  15171. if (texture.samples === samples) {
  15172. return samples;
  15173. }
  15174. var gl = this._gl;
  15175. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15176. // Dispose previous render buffers
  15177. if (texture._depthStencilBuffer) {
  15178. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15179. texture._depthStencilBuffer = null;
  15180. }
  15181. if (texture._MSAAFramebuffer) {
  15182. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15183. texture._MSAAFramebuffer = null;
  15184. }
  15185. if (texture._MSAARenderBuffer) {
  15186. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15187. texture._MSAARenderBuffer = null;
  15188. }
  15189. if (samples > 1) {
  15190. var framebuffer = gl.createFramebuffer();
  15191. if (!framebuffer) {
  15192. throw new Error("Unable to create multi sampled framebuffer");
  15193. }
  15194. texture._MSAAFramebuffer = framebuffer;
  15195. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15196. var colorRenderbuffer = gl.createRenderbuffer();
  15197. if (!colorRenderbuffer) {
  15198. throw new Error("Unable to create multi sampled framebuffer");
  15199. }
  15200. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15201. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15202. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15203. texture._MSAARenderBuffer = colorRenderbuffer;
  15204. }
  15205. else {
  15206. this.bindUnboundFramebuffer(texture._framebuffer);
  15207. }
  15208. texture.samples = samples;
  15209. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15210. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15211. this.bindUnboundFramebuffer(null);
  15212. return samples;
  15213. };
  15214. /**
  15215. * Update the sample count for a given multiple render target texture
  15216. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15217. * @param textures defines the textures to update
  15218. * @param samples defines the sample count to set
  15219. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15220. */
  15221. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15222. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15223. return 1;
  15224. }
  15225. if (textures[0].samples === samples) {
  15226. return samples;
  15227. }
  15228. var gl = this._gl;
  15229. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15230. // Dispose previous render buffers
  15231. if (textures[0]._depthStencilBuffer) {
  15232. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15233. textures[0]._depthStencilBuffer = null;
  15234. }
  15235. if (textures[0]._MSAAFramebuffer) {
  15236. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15237. textures[0]._MSAAFramebuffer = null;
  15238. }
  15239. for (var i = 0; i < textures.length; i++) {
  15240. if (textures[i]._MSAARenderBuffer) {
  15241. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15242. textures[i]._MSAARenderBuffer = null;
  15243. }
  15244. }
  15245. if (samples > 1) {
  15246. var framebuffer = gl.createFramebuffer();
  15247. if (!framebuffer) {
  15248. throw new Error("Unable to create multi sampled framebuffer");
  15249. }
  15250. this.bindUnboundFramebuffer(framebuffer);
  15251. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15252. var attachments = [];
  15253. for (var i = 0; i < textures.length; i++) {
  15254. var texture = textures[i];
  15255. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15256. var colorRenderbuffer = gl.createRenderbuffer();
  15257. if (!colorRenderbuffer) {
  15258. throw new Error("Unable to create multi sampled framebuffer");
  15259. }
  15260. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15261. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15262. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15263. texture._MSAAFramebuffer = framebuffer;
  15264. texture._MSAARenderBuffer = colorRenderbuffer;
  15265. texture.samples = samples;
  15266. texture._depthStencilBuffer = depthStencilBuffer;
  15267. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15268. attachments.push(attachment);
  15269. }
  15270. gl.drawBuffers(attachments);
  15271. }
  15272. else {
  15273. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15274. }
  15275. this.bindUnboundFramebuffer(null);
  15276. return samples;
  15277. };
  15278. /** @hidden */
  15279. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15280. if (faceIndex === void 0) { faceIndex = 0; }
  15281. if (lod === void 0) { lod = 0; }
  15282. var gl = this._gl;
  15283. var target = gl.TEXTURE_2D;
  15284. if (texture.isCube) {
  15285. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15286. }
  15287. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15288. };
  15289. /** @hidden */
  15290. Engine.prototype._uploadDataToTextureDirectly = function (texture, width, height, imageData, faceIndex, lod) {
  15291. if (faceIndex === void 0) { faceIndex = 0; }
  15292. if (lod === void 0) { lod = 0; }
  15293. var gl = this._gl;
  15294. var textureType = this._getWebGLTextureType(texture.type);
  15295. var format = this._getInternalFormat(texture.format);
  15296. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15297. this._unpackFlipY(texture.invertY);
  15298. var target = gl.TEXTURE_2D;
  15299. if (texture.isCube) {
  15300. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15301. }
  15302. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15303. };
  15304. /** @hidden */
  15305. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15306. if (faceIndex === void 0) { faceIndex = 0; }
  15307. if (lod === void 0) { lod = 0; }
  15308. var gl = this._gl;
  15309. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15310. this._bindTextureDirectly(bindTarget, texture, true);
  15311. this._uploadDataToTextureDirectly(texture, texture.width, texture.height, imageData, faceIndex, lod);
  15312. this._bindTextureDirectly(bindTarget, null, true);
  15313. };
  15314. /** @hidden */
  15315. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15316. if (faceIndex === void 0) { faceIndex = 0; }
  15317. if (lod === void 0) { lod = 0; }
  15318. var gl = this._gl;
  15319. var textureType = this._getWebGLTextureType(texture.type);
  15320. var format = this._getInternalFormat(texture.format);
  15321. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15322. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15323. this._bindTextureDirectly(bindTarget, texture, true);
  15324. this._unpackFlipY(texture.invertY);
  15325. var target = gl.TEXTURE_2D;
  15326. if (texture.isCube) {
  15327. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15328. }
  15329. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15330. this._bindTextureDirectly(bindTarget, null, true);
  15331. };
  15332. /**
  15333. * Creates a new render target cube texture
  15334. * @param size defines the size of the texture
  15335. * @param options defines the options used to create the texture
  15336. * @returns a new render target cube texture stored in an InternalTexture
  15337. */
  15338. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15339. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15340. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15341. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15342. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15343. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15344. }
  15345. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15346. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15347. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15348. }
  15349. var gl = this._gl;
  15350. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15351. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15352. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15353. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15354. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15355. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15356. }
  15357. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15358. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15359. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15360. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15361. for (var face = 0; face < 6; face++) {
  15362. 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);
  15363. }
  15364. // Create the framebuffer
  15365. var framebuffer = gl.createFramebuffer();
  15366. this.bindUnboundFramebuffer(framebuffer);
  15367. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15368. // MipMaps
  15369. if (fullOptions.generateMipMaps) {
  15370. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15371. }
  15372. // Unbind
  15373. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15374. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15375. this.bindUnboundFramebuffer(null);
  15376. texture._framebuffer = framebuffer;
  15377. texture.width = size;
  15378. texture.height = size;
  15379. texture.isReady = true;
  15380. texture.isCube = true;
  15381. texture.samples = 1;
  15382. texture.generateMipMaps = fullOptions.generateMipMaps;
  15383. texture.samplingMode = fullOptions.samplingMode;
  15384. texture.type = fullOptions.type;
  15385. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15386. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15387. this._internalTexturesCache.push(texture);
  15388. return texture;
  15389. };
  15390. /**
  15391. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15392. * @param rootUrl defines the url where the file to load is located
  15393. * @param scene defines the current scene
  15394. * @param lodScale defines scale to apply to the mip map selection
  15395. * @param lodOffset defines offset to apply to the mip map selection
  15396. * @param onLoad defines an optional callback raised when the texture is loaded
  15397. * @param onError defines an optional callback raised if there is an issue to load the texture
  15398. * @param format defines the format of the data
  15399. * @param forcedExtension defines the extension to use to pick the right loader
  15400. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15401. * @returns the cube texture as an InternalTexture
  15402. */
  15403. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15404. var _this = this;
  15405. if (onLoad === void 0) { onLoad = null; }
  15406. if (onError === void 0) { onError = null; }
  15407. if (forcedExtension === void 0) { forcedExtension = null; }
  15408. if (createPolynomials === void 0) { createPolynomials = true; }
  15409. var callback = function (loadData) {
  15410. if (!loadData) {
  15411. if (onLoad) {
  15412. onLoad(null);
  15413. }
  15414. return;
  15415. }
  15416. var texture = loadData.texture;
  15417. if (!createPolynomials) {
  15418. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15419. }
  15420. else if (loadData.info.sphericalPolynomial) {
  15421. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15422. }
  15423. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15424. if (_this._caps.textureLOD) {
  15425. // Do not add extra process if texture lod is supported.
  15426. if (onLoad) {
  15427. onLoad(texture);
  15428. }
  15429. return;
  15430. }
  15431. var mipSlices = 3;
  15432. var gl = _this._gl;
  15433. var width = loadData.width;
  15434. if (!width) {
  15435. return;
  15436. }
  15437. var textures = [];
  15438. for (var i = 0; i < mipSlices; i++) {
  15439. //compute LOD from even spacing in smoothness (matching shader calculation)
  15440. var smoothness = i / (mipSlices - 1);
  15441. var roughness = 1 - smoothness;
  15442. var minLODIndex = lodOffset; // roughness = 0
  15443. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15444. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15445. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15446. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15447. glTextureFromLod.isCube = true;
  15448. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15449. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15450. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15451. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15452. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15453. if (loadData.isDDS) {
  15454. var info = loadData.info;
  15455. var data = loadData.data;
  15456. _this._unpackFlipY(info.isCompressed);
  15457. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, true, 6, mipmapIndex);
  15458. }
  15459. else {
  15460. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15461. }
  15462. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15463. // Wrap in a base texture for easy binding.
  15464. var lodTexture = new BABYLON.BaseTexture(scene);
  15465. lodTexture.isCube = true;
  15466. lodTexture._texture = glTextureFromLod;
  15467. glTextureFromLod.isReady = true;
  15468. textures.push(lodTexture);
  15469. }
  15470. texture._lodTextureHigh = textures[2];
  15471. texture._lodTextureMid = textures[1];
  15472. texture._lodTextureLow = textures[0];
  15473. if (onLoad) {
  15474. onLoad(texture);
  15475. }
  15476. };
  15477. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15478. };
  15479. /**
  15480. * Creates a cube texture
  15481. * @param rootUrl defines the url where the files to load is located
  15482. * @param scene defines the current scene
  15483. * @param files defines the list of files to load (1 per face)
  15484. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15485. * @param onLoad defines an optional callback raised when the texture is loaded
  15486. * @param onError defines an optional callback raised if there is an issue to load the texture
  15487. * @param format defines the format of the data
  15488. * @param forcedExtension defines the extension to use to pick the right loader
  15489. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15490. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15491. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15492. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15493. * @returns the cube texture as an InternalTexture
  15494. */
  15495. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15496. var _this = this;
  15497. if (onLoad === void 0) { onLoad = null; }
  15498. if (onError === void 0) { onError = null; }
  15499. if (forcedExtension === void 0) { forcedExtension = null; }
  15500. if (createPolynomials === void 0) { createPolynomials = false; }
  15501. if (lodScale === void 0) { lodScale = 0; }
  15502. if (lodOffset === void 0) { lodOffset = 0; }
  15503. if (fallback === void 0) { fallback = null; }
  15504. var gl = this._gl;
  15505. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15506. texture.isCube = true;
  15507. texture.url = rootUrl;
  15508. texture.generateMipMaps = !noMipmap;
  15509. texture._lodGenerationScale = lodScale;
  15510. texture._lodGenerationOffset = lodOffset;
  15511. if (!this._doNotHandleContextLost) {
  15512. texture._extension = forcedExtension;
  15513. texture._files = files;
  15514. }
  15515. var isKTX = false;
  15516. var isDDS = false;
  15517. var isEnv = false;
  15518. var lastDot = rootUrl.lastIndexOf('.');
  15519. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15520. if (this._textureFormatInUse && !fallback) {
  15521. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15522. isKTX = true;
  15523. }
  15524. else {
  15525. isDDS = (extension === ".dds");
  15526. isEnv = (extension === ".env");
  15527. }
  15528. var onerror = function (request, exception) {
  15529. if (isKTX) {
  15530. //remove the format appended to the rootUrl in the original createCubeTexture call.
  15531. var exp = new RegExp("" + _this._textureFormatInUse + "$");
  15532. _this.createCubeTexture(rootUrl.replace(exp, ""), scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15533. }
  15534. if (onError && request) {
  15535. onError(request.status + " " + request.statusText, exception);
  15536. }
  15537. };
  15538. if (isKTX) {
  15539. this._loadFile(rootUrl, function (data) {
  15540. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15541. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15542. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15543. _this._unpackFlipY(true);
  15544. ktx.uploadLevels(texture, !noMipmap);
  15545. _this.setCubeMapTextureParams(gl, loadMipmap);
  15546. texture.width = ktx.pixelWidth;
  15547. texture.height = ktx.pixelHeight;
  15548. texture.isReady = true;
  15549. }, undefined, undefined, true, onerror);
  15550. }
  15551. else if (isEnv) {
  15552. this._loadFile(rootUrl, function (data) {
  15553. data = data;
  15554. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15555. if (info) {
  15556. texture.width = info.width;
  15557. texture.height = info.width;
  15558. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  15559. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  15560. texture.isReady = true;
  15561. if (onLoad) {
  15562. onLoad();
  15563. }
  15564. });
  15565. }
  15566. else if (onError) {
  15567. onError("Can not parse the environment file", null);
  15568. }
  15569. }, undefined, undefined, true, onerror);
  15570. }
  15571. else if (isDDS) {
  15572. if (files && files.length === 6) {
  15573. this._cascadeLoadFiles(scene, function (imgs) {
  15574. var info;
  15575. var loadMipmap = false;
  15576. var width = 0;
  15577. for (var index = 0; index < imgs.length; index++) {
  15578. var data = imgs[index];
  15579. info = BABYLON.DDSTools.GetDDSInfo(data);
  15580. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15581. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15582. _this._unpackFlipY(info.isCompressed);
  15583. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, loadMipmap, 6, -1, index);
  15584. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15585. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15586. }
  15587. texture.width = info.width;
  15588. texture.height = info.height;
  15589. texture.type = info.textureType;
  15590. width = info.width;
  15591. }
  15592. _this.setCubeMapTextureParams(gl, loadMipmap);
  15593. texture.isReady = true;
  15594. if (onLoad) {
  15595. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15596. }
  15597. }, files, onError);
  15598. }
  15599. else {
  15600. this._loadFile(rootUrl, function (data) {
  15601. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15602. if (createPolynomials) {
  15603. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15604. }
  15605. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15606. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15607. _this._unpackFlipY(info.isCompressed);
  15608. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, loadMipmap, 6);
  15609. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15610. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15611. }
  15612. _this.setCubeMapTextureParams(gl, loadMipmap);
  15613. texture.width = info.width;
  15614. texture.height = info.height;
  15615. texture.isReady = true;
  15616. texture.type = info.textureType;
  15617. if (onLoad) {
  15618. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15619. }
  15620. }, undefined, undefined, true, onerror);
  15621. }
  15622. }
  15623. else {
  15624. if (!files) {
  15625. throw new Error("Cannot load cubemap because files were not defined");
  15626. }
  15627. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15628. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15629. var height = width;
  15630. _this._prepareWorkingCanvas();
  15631. if (!_this._workingCanvas || !_this._workingContext) {
  15632. return;
  15633. }
  15634. _this._workingCanvas.width = width;
  15635. _this._workingCanvas.height = height;
  15636. var faces = [
  15637. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15638. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15639. ];
  15640. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15641. _this._unpackFlipY(false);
  15642. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15643. for (var index = 0; index < faces.length; index++) {
  15644. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15645. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15646. }
  15647. if (!noMipmap) {
  15648. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15649. }
  15650. _this.setCubeMapTextureParams(gl, !noMipmap);
  15651. texture.width = width;
  15652. texture.height = height;
  15653. texture.isReady = true;
  15654. if (format) {
  15655. texture.format = format;
  15656. }
  15657. texture.onLoadedObservable.notifyObservers(texture);
  15658. texture.onLoadedObservable.clear();
  15659. if (onLoad) {
  15660. onLoad();
  15661. }
  15662. }, files, onError);
  15663. }
  15664. this._internalTexturesCache.push(texture);
  15665. return texture;
  15666. };
  15667. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15668. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15669. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15670. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15671. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15672. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15673. // this.resetTextureCache();
  15674. };
  15675. /**
  15676. * Update a raw cube texture
  15677. * @param texture defines the texture to udpdate
  15678. * @param data defines the data to store
  15679. * @param format defines the data format
  15680. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15681. * @param invertY defines if data must be stored with Y axis inverted
  15682. * @param compression defines the compression used (null by default)
  15683. * @param level defines which level of the texture to update
  15684. */
  15685. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15686. if (compression === void 0) { compression = null; }
  15687. if (level === void 0) { level = 0; }
  15688. texture._bufferViewArray = data;
  15689. texture.format = format;
  15690. texture.type = type;
  15691. texture.invertY = invertY;
  15692. texture._compression = compression;
  15693. var gl = this._gl;
  15694. var textureType = this._getWebGLTextureType(type);
  15695. var internalFormat = this._getInternalFormat(format);
  15696. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15697. var needConversion = false;
  15698. if (internalFormat === gl.RGB) {
  15699. internalFormat = gl.RGBA;
  15700. needConversion = true;
  15701. }
  15702. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15703. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15704. if (texture.width % 4 !== 0) {
  15705. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15706. }
  15707. // Data are known to be in +X +Y +Z -X -Y -Z
  15708. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15709. var faceData = data[faceIndex];
  15710. if (compression) {
  15711. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15712. }
  15713. else {
  15714. if (needConversion) {
  15715. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15716. }
  15717. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15718. }
  15719. }
  15720. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15721. if (isPot && texture.generateMipMaps && level === 0) {
  15722. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15723. }
  15724. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15725. // this.resetTextureCache();
  15726. texture.isReady = true;
  15727. };
  15728. /**
  15729. * Creates a new raw cube texture
  15730. * @param data defines the array of data to use to create each face
  15731. * @param size defines the size of the textures
  15732. * @param format defines the format of the data
  15733. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15734. * @param generateMipMaps defines if the engine should generate the mip levels
  15735. * @param invertY defines if data must be stored with Y axis inverted
  15736. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15737. * @param compression defines the compression used (null by default)
  15738. * @returns the cube texture as an InternalTexture
  15739. */
  15740. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15741. if (compression === void 0) { compression = null; }
  15742. var gl = this._gl;
  15743. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15744. texture.isCube = true;
  15745. texture.generateMipMaps = generateMipMaps;
  15746. texture.format = format;
  15747. texture.type = type;
  15748. if (!this._doNotHandleContextLost) {
  15749. texture._bufferViewArray = data;
  15750. }
  15751. var textureType = this._getWebGLTextureType(type);
  15752. var internalFormat = this._getInternalFormat(format);
  15753. if (internalFormat === gl.RGB) {
  15754. internalFormat = gl.RGBA;
  15755. }
  15756. var width = size;
  15757. var height = width;
  15758. texture.width = width;
  15759. texture.height = height;
  15760. // Double check on POT to generate Mips.
  15761. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15762. if (!isPot) {
  15763. generateMipMaps = false;
  15764. }
  15765. // Upload data if needed. The texture won't be ready until then.
  15766. if (data) {
  15767. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15768. }
  15769. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15770. // Filters
  15771. if (data && generateMipMaps) {
  15772. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15773. }
  15774. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15775. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15776. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15777. }
  15778. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15779. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15780. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15781. }
  15782. else {
  15783. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15784. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15785. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15786. }
  15787. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15788. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15789. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15790. return texture;
  15791. };
  15792. /**
  15793. * Creates a new raw cube texture from a specified url
  15794. * @param url defines the url where the data is located
  15795. * @param scene defines the current scene
  15796. * @param size defines the size of the textures
  15797. * @param format defines the format of the data
  15798. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15799. * @param noMipmap defines if the engine should avoid generating the mip levels
  15800. * @param callback defines a callback used to extract texture data from loaded data
  15801. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15802. * @param onLoad defines a callback called when texture is loaded
  15803. * @param onError defines a callback called if there is an error
  15804. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15805. * @param invertY defines if data must be stored with Y axis inverted
  15806. * @returns the cube texture as an InternalTexture
  15807. */
  15808. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15809. var _this = this;
  15810. if (onLoad === void 0) { onLoad = null; }
  15811. if (onError === void 0) { onError = null; }
  15812. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15813. if (invertY === void 0) { invertY = false; }
  15814. var gl = this._gl;
  15815. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15816. scene._addPendingData(texture);
  15817. texture.url = url;
  15818. this._internalTexturesCache.push(texture);
  15819. var onerror = function (request, exception) {
  15820. scene._removePendingData(texture);
  15821. if (onError && request) {
  15822. onError(request.status + " " + request.statusText, exception);
  15823. }
  15824. };
  15825. var internalCallback = function (data) {
  15826. var width = texture.width;
  15827. var faceDataArrays = callback(data);
  15828. if (!faceDataArrays) {
  15829. return;
  15830. }
  15831. if (mipmapGenerator) {
  15832. var textureType = _this._getWebGLTextureType(type);
  15833. var internalFormat = _this._getInternalFormat(format);
  15834. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15835. var needConversion = false;
  15836. if (internalFormat === gl.RGB) {
  15837. internalFormat = gl.RGBA;
  15838. needConversion = true;
  15839. }
  15840. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15841. _this._unpackFlipY(false);
  15842. var mipData = mipmapGenerator(faceDataArrays);
  15843. for (var level = 0; level < mipData.length; level++) {
  15844. var mipSize = width >> level;
  15845. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15846. var mipFaceData = mipData[level][faceIndex];
  15847. if (needConversion) {
  15848. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15849. }
  15850. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15851. }
  15852. }
  15853. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15854. }
  15855. else {
  15856. texture.generateMipMaps = !noMipmap;
  15857. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15858. }
  15859. texture.isReady = true;
  15860. // this.resetTextureCache();
  15861. scene._removePendingData(texture);
  15862. if (onLoad) {
  15863. onLoad();
  15864. }
  15865. };
  15866. this._loadFile(url, function (data) {
  15867. internalCallback(data);
  15868. }, undefined, scene.database, true, onerror);
  15869. return texture;
  15870. };
  15871. ;
  15872. /**
  15873. * Update a raw 3D texture
  15874. * @param texture defines the texture to update
  15875. * @param data defines the data to store
  15876. * @param format defines the data format
  15877. * @param invertY defines if data must be stored with Y axis inverted
  15878. * @param compression defines the used compression (can be null)
  15879. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15880. */
  15881. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15882. if (compression === void 0) { compression = null; }
  15883. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15884. var internalType = this._getWebGLTextureType(textureType);
  15885. var internalFormat = this._getInternalFormat(format);
  15886. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15887. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15888. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15889. if (!this._doNotHandleContextLost) {
  15890. texture._bufferView = data;
  15891. texture.format = format;
  15892. texture.invertY = invertY;
  15893. texture._compression = compression;
  15894. }
  15895. if (texture.width % 4 !== 0) {
  15896. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15897. }
  15898. if (compression && data) {
  15899. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15900. }
  15901. else {
  15902. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15903. }
  15904. if (texture.generateMipMaps) {
  15905. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15906. }
  15907. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15908. // this.resetTextureCache();
  15909. texture.isReady = true;
  15910. };
  15911. /**
  15912. * Creates a new raw 3D texture
  15913. * @param data defines the data used to create the texture
  15914. * @param width defines the width of the texture
  15915. * @param height defines the height of the texture
  15916. * @param depth defines the depth of the texture
  15917. * @param format defines the format of the texture
  15918. * @param generateMipMaps defines if the engine must generate mip levels
  15919. * @param invertY defines if data must be stored with Y axis inverted
  15920. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15921. * @param compression defines the compressed used (can be null)
  15922. * @param textureType defines the compressed used (can be null)
  15923. * @returns a new raw 3D texture (stored in an InternalTexture)
  15924. */
  15925. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15926. if (compression === void 0) { compression = null; }
  15927. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15928. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15929. texture.baseWidth = width;
  15930. texture.baseHeight = height;
  15931. texture.baseDepth = depth;
  15932. texture.width = width;
  15933. texture.height = height;
  15934. texture.depth = depth;
  15935. texture.format = format;
  15936. texture.type = textureType;
  15937. texture.generateMipMaps = generateMipMaps;
  15938. texture.samplingMode = samplingMode;
  15939. texture.is3D = true;
  15940. if (!this._doNotHandleContextLost) {
  15941. texture._bufferView = data;
  15942. }
  15943. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  15944. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15945. // Filters
  15946. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15947. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15948. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15949. if (generateMipMaps) {
  15950. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15951. }
  15952. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15953. this._internalTexturesCache.push(texture);
  15954. return texture;
  15955. };
  15956. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15957. var gl = this._gl;
  15958. if (!gl) {
  15959. return;
  15960. }
  15961. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  15962. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15963. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15964. if (!noMipmap && !isCompressed) {
  15965. gl.generateMipmap(gl.TEXTURE_2D);
  15966. }
  15967. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15968. // this.resetTextureCache();
  15969. if (scene) {
  15970. scene._removePendingData(texture);
  15971. }
  15972. texture.onLoadedObservable.notifyObservers(texture);
  15973. texture.onLoadedObservable.clear();
  15974. };
  15975. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15976. var _this = this;
  15977. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15978. var maxTextureSize = this.getCaps().maxTextureSize;
  15979. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  15980. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  15981. var gl = this._gl;
  15982. if (!gl) {
  15983. return;
  15984. }
  15985. if (!texture._webGLTexture) {
  15986. // this.resetTextureCache();
  15987. if (scene) {
  15988. scene._removePendingData(texture);
  15989. }
  15990. return;
  15991. }
  15992. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15993. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15994. texture.baseWidth = width;
  15995. texture.baseHeight = height;
  15996. texture.width = potWidth;
  15997. texture.height = potHeight;
  15998. texture.isReady = true;
  15999. if (processFunction(potWidth, potHeight, function () {
  16000. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16001. })) {
  16002. // Returning as texture needs extra async steps
  16003. return;
  16004. }
  16005. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16006. };
  16007. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16008. // Create new RGBA data container.
  16009. var rgbaData;
  16010. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16011. rgbaData = new Float32Array(width * height * 4);
  16012. }
  16013. else {
  16014. rgbaData = new Uint32Array(width * height * 4);
  16015. }
  16016. // Convert each pixel.
  16017. for (var x = 0; x < width; x++) {
  16018. for (var y = 0; y < height; y++) {
  16019. var index = (y * width + x) * 3;
  16020. var newIndex = (y * width + x) * 4;
  16021. // Map Old Value to new value.
  16022. rgbaData[newIndex + 0] = rgbData[index + 0];
  16023. rgbaData[newIndex + 1] = rgbData[index + 1];
  16024. rgbaData[newIndex + 2] = rgbData[index + 2];
  16025. // Add fully opaque alpha channel.
  16026. rgbaData[newIndex + 3] = 1;
  16027. }
  16028. }
  16029. return rgbaData;
  16030. };
  16031. /** @hidden */
  16032. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16033. var gl = this._gl;
  16034. if (texture._framebuffer) {
  16035. gl.deleteFramebuffer(texture._framebuffer);
  16036. texture._framebuffer = null;
  16037. }
  16038. if (texture._depthStencilBuffer) {
  16039. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16040. texture._depthStencilBuffer = null;
  16041. }
  16042. if (texture._MSAAFramebuffer) {
  16043. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16044. texture._MSAAFramebuffer = null;
  16045. }
  16046. if (texture._MSAARenderBuffer) {
  16047. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16048. texture._MSAARenderBuffer = null;
  16049. }
  16050. };
  16051. /** @hidden */
  16052. Engine.prototype._releaseTexture = function (texture) {
  16053. var gl = this._gl;
  16054. this._releaseFramebufferObjects(texture);
  16055. gl.deleteTexture(texture._webGLTexture);
  16056. // Unbind channels
  16057. this.unbindAllTextures();
  16058. var index = this._internalTexturesCache.indexOf(texture);
  16059. if (index !== -1) {
  16060. this._internalTexturesCache.splice(index, 1);
  16061. }
  16062. // Integrated fixed lod samplers.
  16063. if (texture._lodTextureHigh) {
  16064. texture._lodTextureHigh.dispose();
  16065. }
  16066. if (texture._lodTextureMid) {
  16067. texture._lodTextureMid.dispose();
  16068. }
  16069. if (texture._lodTextureLow) {
  16070. texture._lodTextureLow.dispose();
  16071. }
  16072. // Set output texture of post process to null if the texture has been released/disposed
  16073. this.scenes.forEach(function (scene) {
  16074. scene.postProcesses.forEach(function (postProcess) {
  16075. if (postProcess._outputTexture == texture) {
  16076. postProcess._outputTexture = null;
  16077. }
  16078. });
  16079. scene.cameras.forEach(function (camera) {
  16080. camera._postProcesses.forEach(function (postProcess) {
  16081. if (postProcess) {
  16082. if (postProcess._outputTexture == texture) {
  16083. postProcess._outputTexture = null;
  16084. }
  16085. }
  16086. });
  16087. });
  16088. });
  16089. };
  16090. Engine.prototype.setProgram = function (program) {
  16091. if (this._currentProgram !== program) {
  16092. this._gl.useProgram(program);
  16093. this._currentProgram = program;
  16094. }
  16095. };
  16096. /**
  16097. * Binds an effect to the webGL context
  16098. * @param effect defines the effect to bind
  16099. */
  16100. Engine.prototype.bindSamplers = function (effect) {
  16101. this.setProgram(effect.getProgram());
  16102. var samplers = effect.getSamplers();
  16103. for (var index = 0; index < samplers.length; index++) {
  16104. var uniform = effect.getUniform(samplers[index]);
  16105. if (uniform) {
  16106. this._boundUniforms[index] = uniform;
  16107. }
  16108. }
  16109. this._currentEffect = null;
  16110. };
  16111. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16112. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16113. return;
  16114. }
  16115. // Remove
  16116. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16117. // Bind last to it
  16118. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16119. // Bind to dummy
  16120. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16121. };
  16122. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16123. if (!internalTexture) {
  16124. return -1;
  16125. }
  16126. internalTexture._initialSlot = channel;
  16127. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16128. if (channel !== internalTexture._designatedSlot) {
  16129. this._textureCollisions.addCount(1, false);
  16130. }
  16131. }
  16132. else {
  16133. if (channel !== internalTexture._designatedSlot) {
  16134. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16135. return internalTexture._designatedSlot;
  16136. }
  16137. else {
  16138. // No slot for this texture, let's pick a new one (if we find a free slot)
  16139. if (this._nextFreeTextureSlots.length) {
  16140. return this._nextFreeTextureSlots[0];
  16141. }
  16142. // We need to recycle the oldest bound texture, sorry.
  16143. this._textureCollisions.addCount(1, false);
  16144. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16145. }
  16146. }
  16147. }
  16148. return channel;
  16149. };
  16150. Engine.prototype._linkTrackers = function (previous, next) {
  16151. previous.next = next;
  16152. next.previous = previous;
  16153. };
  16154. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16155. var currentSlot = internalTexture._designatedSlot;
  16156. if (currentSlot === -1) {
  16157. return -1;
  16158. }
  16159. internalTexture._designatedSlot = -1;
  16160. if (this.disableTextureBindingOptimization) {
  16161. return -1;
  16162. }
  16163. // Remove from bound list
  16164. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16165. // Free the slot
  16166. this._boundTexturesCache[currentSlot] = null;
  16167. this._nextFreeTextureSlots.push(currentSlot);
  16168. return currentSlot;
  16169. };
  16170. Engine.prototype._activateCurrentTexture = function () {
  16171. if (this._currentTextureChannel !== this._activeChannel) {
  16172. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16173. this._currentTextureChannel = this._activeChannel;
  16174. }
  16175. };
  16176. /** @hidden */
  16177. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16178. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16179. if (force === void 0) { force = false; }
  16180. var wasPreviouslyBound = false;
  16181. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16182. this._activeChannel = texture._designatedSlot;
  16183. }
  16184. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16185. var isTextureForRendering = texture && texture._initialSlot > -1;
  16186. if (currentTextureBound !== texture || force) {
  16187. if (currentTextureBound) {
  16188. this._removeDesignatedSlot(currentTextureBound);
  16189. }
  16190. this._activateCurrentTexture();
  16191. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16192. this._boundTexturesCache[this._activeChannel] = texture;
  16193. if (texture) {
  16194. if (!this.disableTextureBindingOptimization) {
  16195. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16196. if (slotIndex > -1) {
  16197. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16198. }
  16199. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16200. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16201. }
  16202. texture._designatedSlot = this._activeChannel;
  16203. }
  16204. }
  16205. else if (forTextureDataUpdate) {
  16206. wasPreviouslyBound = true;
  16207. this._activateCurrentTexture();
  16208. }
  16209. if (isTextureForRendering && !forTextureDataUpdate) {
  16210. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16211. }
  16212. return wasPreviouslyBound;
  16213. };
  16214. /** @hidden */
  16215. Engine.prototype._bindTexture = function (channel, texture) {
  16216. if (channel < 0) {
  16217. return;
  16218. }
  16219. if (texture) {
  16220. channel = this._getCorrectTextureChannel(channel, texture);
  16221. }
  16222. this._activeChannel = channel;
  16223. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16224. };
  16225. /**
  16226. * Sets a texture to the webGL context from a postprocess
  16227. * @param channel defines the channel to use
  16228. * @param postProcess defines the source postprocess
  16229. */
  16230. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16231. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16232. };
  16233. /**
  16234. * Binds the output of the passed in post process to the texture channel specified
  16235. * @param channel The channel the texture should be bound to
  16236. * @param postProcess The post process which's output should be bound
  16237. */
  16238. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16239. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16240. };
  16241. /**
  16242. * Unbind all textures from the webGL context
  16243. */
  16244. Engine.prototype.unbindAllTextures = function () {
  16245. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16246. this._activeChannel = channel;
  16247. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16248. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16249. if (this.webGLVersion > 1) {
  16250. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16251. }
  16252. }
  16253. };
  16254. /**
  16255. * Sets a texture to the according uniform.
  16256. * @param channel The texture channel
  16257. * @param uniform The uniform to set
  16258. * @param texture The texture to apply
  16259. */
  16260. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16261. if (channel < 0) {
  16262. return;
  16263. }
  16264. if (uniform) {
  16265. this._boundUniforms[channel] = uniform;
  16266. }
  16267. this._setTexture(channel, texture);
  16268. };
  16269. /**
  16270. * Sets a depth stencil texture from a render target to the according uniform.
  16271. * @param channel The texture channel
  16272. * @param uniform The uniform to set
  16273. * @param texture The render target texture containing the depth stencil texture to apply
  16274. */
  16275. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16276. if (channel < 0) {
  16277. return;
  16278. }
  16279. if (uniform) {
  16280. this._boundUniforms[channel] = uniform;
  16281. }
  16282. if (!texture || !texture.depthStencilTexture) {
  16283. this._setTexture(channel, null);
  16284. }
  16285. else {
  16286. this._setTexture(channel, texture, false, true);
  16287. }
  16288. };
  16289. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16290. var uniform = this._boundUniforms[sourceSlot];
  16291. if (uniform._currentState === destination) {
  16292. return;
  16293. }
  16294. this._gl.uniform1i(uniform, destination);
  16295. uniform._currentState = destination;
  16296. };
  16297. Engine.prototype._getTextureWrapMode = function (mode) {
  16298. switch (mode) {
  16299. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16300. return this._gl.REPEAT;
  16301. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16302. return this._gl.CLAMP_TO_EDGE;
  16303. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16304. return this._gl.MIRRORED_REPEAT;
  16305. }
  16306. return this._gl.REPEAT;
  16307. };
  16308. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16309. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16310. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16311. // Not ready?
  16312. if (!texture) {
  16313. if (this._boundTexturesCache[channel] != null) {
  16314. this._activeChannel = channel;
  16315. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16316. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16317. if (this.webGLVersion > 1) {
  16318. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16319. }
  16320. }
  16321. return false;
  16322. }
  16323. // Video
  16324. if (texture.video) {
  16325. this._activeChannel = channel;
  16326. texture.update();
  16327. }
  16328. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16329. texture.delayLoad();
  16330. return false;
  16331. }
  16332. var internalTexture;
  16333. if (depthStencilTexture) {
  16334. internalTexture = texture.depthStencilTexture;
  16335. }
  16336. else if (texture.isReady()) {
  16337. internalTexture = texture.getInternalTexture();
  16338. }
  16339. else if (texture.isCube) {
  16340. internalTexture = this.emptyCubeTexture;
  16341. }
  16342. else if (texture.is3D) {
  16343. internalTexture = this.emptyTexture3D;
  16344. }
  16345. else {
  16346. internalTexture = this.emptyTexture;
  16347. }
  16348. if (!isPartOfTextureArray) {
  16349. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16350. }
  16351. var needToBind = true;
  16352. if (this._boundTexturesCache[channel] === internalTexture) {
  16353. this._moveBoundTextureOnTop(internalTexture);
  16354. if (!isPartOfTextureArray) {
  16355. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16356. }
  16357. needToBind = false;
  16358. }
  16359. this._activeChannel = channel;
  16360. if (internalTexture && internalTexture.is3D) {
  16361. if (needToBind) {
  16362. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16363. }
  16364. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16365. internalTexture._cachedWrapU = texture.wrapU;
  16366. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16367. }
  16368. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16369. internalTexture._cachedWrapV = texture.wrapV;
  16370. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16371. }
  16372. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16373. internalTexture._cachedWrapR = texture.wrapR;
  16374. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16375. }
  16376. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16377. }
  16378. else if (internalTexture && internalTexture.isCube) {
  16379. if (needToBind) {
  16380. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16381. }
  16382. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16383. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16384. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16385. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16386. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16387. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16388. }
  16389. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16390. }
  16391. else {
  16392. if (needToBind) {
  16393. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16394. }
  16395. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16396. internalTexture._cachedWrapU = texture.wrapU;
  16397. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16398. }
  16399. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16400. internalTexture._cachedWrapV = texture.wrapV;
  16401. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16402. }
  16403. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16404. }
  16405. return true;
  16406. };
  16407. /**
  16408. * Sets an array of texture to the webGL context
  16409. * @param channel defines the channel where the texture array must be set
  16410. * @param uniform defines the associated uniform location
  16411. * @param textures defines the array of textures to bind
  16412. */
  16413. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16414. if (channel < 0 || !uniform) {
  16415. return;
  16416. }
  16417. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16418. this._textureUnits = new Int32Array(textures.length);
  16419. }
  16420. for (var i = 0; i < textures.length; i++) {
  16421. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16422. }
  16423. this._gl.uniform1iv(uniform, this._textureUnits);
  16424. for (var index = 0; index < textures.length; index++) {
  16425. this._setTexture(this._textureUnits[index], textures[index], true);
  16426. }
  16427. };
  16428. /** @hidden */
  16429. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16430. var internalTexture = texture.getInternalTexture();
  16431. if (!internalTexture) {
  16432. return;
  16433. }
  16434. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16435. var value = texture.anisotropicFilteringLevel;
  16436. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16437. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16438. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16439. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16440. }
  16441. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16442. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16443. internalTexture._cachedAnisotropicFilteringLevel = value;
  16444. }
  16445. };
  16446. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16447. this._bindTextureDirectly(target, texture, true, true);
  16448. this._gl.texParameterf(target, parameter, value);
  16449. };
  16450. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16451. if (texture) {
  16452. this._bindTextureDirectly(target, texture, true, true);
  16453. }
  16454. this._gl.texParameteri(target, parameter, value);
  16455. };
  16456. /**
  16457. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16458. * @param x defines the x coordinate of the rectangle where pixels must be read
  16459. * @param y defines the y coordinate of the rectangle where pixels must be read
  16460. * @param width defines the width of the rectangle where pixels must be read
  16461. * @param height defines the height of the rectangle where pixels must be read
  16462. * @returns a Uint8Array containing RGBA colors
  16463. */
  16464. Engine.prototype.readPixels = function (x, y, width, height) {
  16465. var data = new Uint8Array(height * width * 4);
  16466. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16467. return data;
  16468. };
  16469. /**
  16470. * Add an externaly attached data from its key.
  16471. * This method call will fail and return false, if such key already exists.
  16472. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16473. * @param key the unique key that identifies the data
  16474. * @param data the data object to associate to the key for this Engine instance
  16475. * @return true if no such key were already present and the data was added successfully, false otherwise
  16476. */
  16477. Engine.prototype.addExternalData = function (key, data) {
  16478. if (!this._externalData) {
  16479. this._externalData = new BABYLON.StringDictionary();
  16480. }
  16481. return this._externalData.add(key, data);
  16482. };
  16483. /**
  16484. * Get an externaly attached data from its key
  16485. * @param key the unique key that identifies the data
  16486. * @return the associated data, if present (can be null), or undefined if not present
  16487. */
  16488. Engine.prototype.getExternalData = function (key) {
  16489. if (!this._externalData) {
  16490. this._externalData = new BABYLON.StringDictionary();
  16491. }
  16492. return this._externalData.get(key);
  16493. };
  16494. /**
  16495. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16496. * @param key the unique key that identifies the data
  16497. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16498. * @return the associated data, can be null if the factory returned null.
  16499. */
  16500. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16501. if (!this._externalData) {
  16502. this._externalData = new BABYLON.StringDictionary();
  16503. }
  16504. return this._externalData.getOrAddWithFactory(key, factory);
  16505. };
  16506. /**
  16507. * Remove an externaly attached data from the Engine instance
  16508. * @param key the unique key that identifies the data
  16509. * @return true if the data was successfully removed, false if it doesn't exist
  16510. */
  16511. Engine.prototype.removeExternalData = function (key) {
  16512. if (!this._externalData) {
  16513. this._externalData = new BABYLON.StringDictionary();
  16514. }
  16515. return this._externalData.remove(key);
  16516. };
  16517. /**
  16518. * Unbind all vertex attributes from the webGL context
  16519. */
  16520. Engine.prototype.unbindAllAttributes = function () {
  16521. if (this._mustWipeVertexAttributes) {
  16522. this._mustWipeVertexAttributes = false;
  16523. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16524. this._gl.disableVertexAttribArray(i);
  16525. this._vertexAttribArraysEnabled[i] = false;
  16526. this._currentBufferPointers[i].active = false;
  16527. }
  16528. return;
  16529. }
  16530. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16531. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16532. continue;
  16533. }
  16534. this._gl.disableVertexAttribArray(i);
  16535. this._vertexAttribArraysEnabled[i] = false;
  16536. this._currentBufferPointers[i].active = false;
  16537. }
  16538. };
  16539. /**
  16540. * 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
  16541. */
  16542. Engine.prototype.releaseEffects = function () {
  16543. for (var name in this._compiledEffects) {
  16544. this._deleteProgram(this._compiledEffects[name]._program);
  16545. }
  16546. this._compiledEffects = {};
  16547. };
  16548. /**
  16549. * Dispose and release all associated resources
  16550. */
  16551. Engine.prototype.dispose = function () {
  16552. this.hideLoadingUI();
  16553. this.stopRenderLoop();
  16554. // Release postProcesses
  16555. while (this.postProcesses.length) {
  16556. this.postProcesses[0].dispose();
  16557. }
  16558. // Empty texture
  16559. if (this._emptyTexture) {
  16560. this._releaseTexture(this._emptyTexture);
  16561. this._emptyTexture = null;
  16562. }
  16563. if (this._emptyCubeTexture) {
  16564. this._releaseTexture(this._emptyCubeTexture);
  16565. this._emptyCubeTexture = null;
  16566. }
  16567. // Rescale PP
  16568. if (this._rescalePostProcess) {
  16569. this._rescalePostProcess.dispose();
  16570. }
  16571. // Release scenes
  16572. while (this.scenes.length) {
  16573. this.scenes[0].dispose();
  16574. }
  16575. // Release audio engine
  16576. if (Engine.audioEngine) {
  16577. Engine.audioEngine.dispose();
  16578. }
  16579. // Release effects
  16580. this.releaseEffects();
  16581. // Unbind
  16582. this.unbindAllAttributes();
  16583. this._boundUniforms = [];
  16584. if (this._dummyFramebuffer) {
  16585. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16586. }
  16587. //WebVR
  16588. this.disableVR();
  16589. // Events
  16590. if (BABYLON.Tools.IsWindowObjectExist()) {
  16591. window.removeEventListener("blur", this._onBlur);
  16592. window.removeEventListener("focus", this._onFocus);
  16593. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16594. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16595. if (this._renderingCanvas) {
  16596. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16597. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16598. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16599. if (!this._doNotHandleContextLost) {
  16600. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16601. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16602. }
  16603. }
  16604. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16605. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16606. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16607. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16608. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16609. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16610. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16611. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16612. if (this._onVrDisplayConnect) {
  16613. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16614. if (this._onVrDisplayDisconnect) {
  16615. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16616. }
  16617. if (this._onVrDisplayPresentChange) {
  16618. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16619. }
  16620. this._onVrDisplayConnect = null;
  16621. this._onVrDisplayDisconnect = null;
  16622. }
  16623. }
  16624. // Remove from Instances
  16625. var index = Engine.Instances.indexOf(this);
  16626. if (index >= 0) {
  16627. Engine.Instances.splice(index, 1);
  16628. }
  16629. this._workingCanvas = null;
  16630. this._workingContext = null;
  16631. this._currentBufferPointers = [];
  16632. this._renderingCanvas = null;
  16633. this._currentProgram = null;
  16634. this._bindedRenderFunction = null;
  16635. this.onResizeObservable.clear();
  16636. this.onCanvasBlurObservable.clear();
  16637. this.onCanvasFocusObservable.clear();
  16638. this.onCanvasPointerOutObservable.clear();
  16639. this.onBeginFrameObservable.clear();
  16640. this.onEndFrameObservable.clear();
  16641. BABYLON.Effect.ResetCache();
  16642. // Abort active requests
  16643. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16644. var request = _a[_i];
  16645. request.abort();
  16646. }
  16647. };
  16648. // Loading screen
  16649. /**
  16650. * Display the loading screen
  16651. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16652. */
  16653. Engine.prototype.displayLoadingUI = function () {
  16654. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16655. return;
  16656. }
  16657. var loadingScreen = this.loadingScreen;
  16658. if (loadingScreen) {
  16659. loadingScreen.displayLoadingUI();
  16660. }
  16661. };
  16662. /**
  16663. * Hide the loading screen
  16664. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16665. */
  16666. Engine.prototype.hideLoadingUI = function () {
  16667. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16668. return;
  16669. }
  16670. var loadingScreen = this.loadingScreen;
  16671. if (loadingScreen) {
  16672. loadingScreen.hideLoadingUI();
  16673. }
  16674. };
  16675. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16676. /**
  16677. * Gets the current loading screen object
  16678. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16679. */
  16680. get: function () {
  16681. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16682. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16683. return this._loadingScreen;
  16684. },
  16685. /**
  16686. * Sets the current loading screen object
  16687. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16688. */
  16689. set: function (loadingScreen) {
  16690. this._loadingScreen = loadingScreen;
  16691. },
  16692. enumerable: true,
  16693. configurable: true
  16694. });
  16695. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16696. /**
  16697. * Sets the current loading screen text
  16698. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16699. */
  16700. set: function (text) {
  16701. this.loadingScreen.loadingUIText = text;
  16702. },
  16703. enumerable: true,
  16704. configurable: true
  16705. });
  16706. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16707. /**
  16708. * Sets the current loading screen background color
  16709. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16710. */
  16711. set: function (color) {
  16712. this.loadingScreen.loadingUIBackgroundColor = color;
  16713. },
  16714. enumerable: true,
  16715. configurable: true
  16716. });
  16717. /**
  16718. * Attach a new callback raised when context lost event is fired
  16719. * @param callback defines the callback to call
  16720. */
  16721. Engine.prototype.attachContextLostEvent = function (callback) {
  16722. if (this._renderingCanvas) {
  16723. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16724. }
  16725. };
  16726. /**
  16727. * Attach a new callback raised when context restored event is fired
  16728. * @param callback defines the callback to call
  16729. */
  16730. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16731. if (this._renderingCanvas) {
  16732. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16733. }
  16734. };
  16735. /**
  16736. * Gets the source code of the vertex shader associated with a specific webGL program
  16737. * @param program defines the program to use
  16738. * @returns a string containing the source code of the vertex shader associated with the program
  16739. */
  16740. Engine.prototype.getVertexShaderSource = function (program) {
  16741. var shaders = this._gl.getAttachedShaders(program);
  16742. if (!shaders) {
  16743. return null;
  16744. }
  16745. return this._gl.getShaderSource(shaders[0]);
  16746. };
  16747. /**
  16748. * Gets the source code of the fragment shader associated with a specific webGL program
  16749. * @param program defines the program to use
  16750. * @returns a string containing the source code of the fragment shader associated with the program
  16751. */
  16752. Engine.prototype.getFragmentShaderSource = function (program) {
  16753. var shaders = this._gl.getAttachedShaders(program);
  16754. if (!shaders) {
  16755. return null;
  16756. }
  16757. return this._gl.getShaderSource(shaders[1]);
  16758. };
  16759. /**
  16760. * Get the current error code of the webGL context
  16761. * @returns the error code
  16762. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16763. */
  16764. Engine.prototype.getError = function () {
  16765. return this._gl.getError();
  16766. };
  16767. // FPS
  16768. /**
  16769. * Gets the current framerate
  16770. * @returns a number representing the framerate
  16771. */
  16772. Engine.prototype.getFps = function () {
  16773. return this._fps;
  16774. };
  16775. /**
  16776. * Gets the time spent between current and previous frame
  16777. * @returns a number representing the delta time in ms
  16778. */
  16779. Engine.prototype.getDeltaTime = function () {
  16780. return this._deltaTime;
  16781. };
  16782. Engine.prototype._measureFps = function () {
  16783. this._performanceMonitor.sampleFrame();
  16784. this._fps = this._performanceMonitor.averageFPS;
  16785. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16786. };
  16787. /** @hidden */
  16788. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16789. if (faceIndex === void 0) { faceIndex = -1; }
  16790. if (level === void 0) { level = 0; }
  16791. var gl = this._gl;
  16792. if (!this._dummyFramebuffer) {
  16793. var dummy = gl.createFramebuffer();
  16794. if (!dummy) {
  16795. throw new Error("Unable to create dummy framebuffer");
  16796. }
  16797. this._dummyFramebuffer = dummy;
  16798. }
  16799. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16800. if (faceIndex > -1) {
  16801. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16802. }
  16803. else {
  16804. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16805. }
  16806. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16807. var buffer;
  16808. switch (readType) {
  16809. case gl.UNSIGNED_BYTE:
  16810. buffer = new Uint8Array(4 * width * height);
  16811. readType = gl.UNSIGNED_BYTE;
  16812. break;
  16813. default:
  16814. buffer = new Float32Array(4 * width * height);
  16815. readType = gl.FLOAT;
  16816. break;
  16817. }
  16818. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16819. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16820. return buffer;
  16821. };
  16822. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16823. if (this._webGLVersion > 1) {
  16824. return this._caps.colorBufferFloat;
  16825. }
  16826. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16827. };
  16828. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16829. if (this._webGLVersion > 1) {
  16830. return this._caps.colorBufferFloat;
  16831. }
  16832. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16833. };
  16834. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16835. Engine.prototype._canRenderToFramebuffer = function (type) {
  16836. var gl = this._gl;
  16837. //clear existing errors
  16838. while (gl.getError() !== gl.NO_ERROR) { }
  16839. var successful = true;
  16840. var texture = gl.createTexture();
  16841. gl.bindTexture(gl.TEXTURE_2D, texture);
  16842. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16843. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16844. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16845. var fb = gl.createFramebuffer();
  16846. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16847. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16848. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16849. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16850. successful = successful && (gl.getError() === gl.NO_ERROR);
  16851. //try render by clearing frame buffer's color buffer
  16852. if (successful) {
  16853. gl.clear(gl.COLOR_BUFFER_BIT);
  16854. successful = successful && (gl.getError() === gl.NO_ERROR);
  16855. }
  16856. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16857. if (successful) {
  16858. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16859. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16860. var readFormat = gl.RGBA;
  16861. var readType = gl.UNSIGNED_BYTE;
  16862. var buffer = new Uint8Array(4);
  16863. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16864. successful = successful && (gl.getError() === gl.NO_ERROR);
  16865. }
  16866. //clean up
  16867. gl.deleteTexture(texture);
  16868. gl.deleteFramebuffer(fb);
  16869. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16870. //clear accumulated errors
  16871. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16872. return successful;
  16873. };
  16874. /** @hidden */
  16875. Engine.prototype._getWebGLTextureType = function (type) {
  16876. if (type === Engine.TEXTURETYPE_FLOAT) {
  16877. return this._gl.FLOAT;
  16878. }
  16879. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16880. // Add Half Float Constant.
  16881. return this._gl.HALF_FLOAT_OES;
  16882. }
  16883. return this._gl.UNSIGNED_BYTE;
  16884. };
  16885. ;
  16886. Engine.prototype._getInternalFormat = function (format) {
  16887. var internalFormat = this._gl.RGBA;
  16888. switch (format) {
  16889. case Engine.TEXTUREFORMAT_ALPHA:
  16890. internalFormat = this._gl.ALPHA;
  16891. break;
  16892. case Engine.TEXTUREFORMAT_LUMINANCE:
  16893. internalFormat = this._gl.LUMINANCE;
  16894. break;
  16895. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16896. internalFormat = this._gl.LUMINANCE_ALPHA;
  16897. break;
  16898. case Engine.TEXTUREFORMAT_RGB:
  16899. internalFormat = this._gl.RGB;
  16900. break;
  16901. case Engine.TEXTUREFORMAT_RGBA:
  16902. internalFormat = this._gl.RGBA;
  16903. break;
  16904. case Engine.TEXTUREFORMAT_R:
  16905. internalFormat = this._gl.RED;
  16906. break;
  16907. case Engine.TEXTUREFORMAT_RG:
  16908. internalFormat = this._gl.RG;
  16909. break;
  16910. }
  16911. return internalFormat;
  16912. };
  16913. /** @hidden */
  16914. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16915. if (this._webGLVersion === 1) {
  16916. if (format !== undefined) {
  16917. switch (format) {
  16918. case Engine.TEXTUREFORMAT_LUMINANCE:
  16919. return this._gl.LUMINANCE;
  16920. case Engine.TEXTUREFORMAT_ALPHA:
  16921. return this._gl.ALPHA;
  16922. }
  16923. }
  16924. return this._gl.RGBA;
  16925. }
  16926. if (type === Engine.TEXTURETYPE_FLOAT) {
  16927. if (format !== undefined) {
  16928. switch (format) {
  16929. case Engine.TEXTUREFORMAT_R:
  16930. return this._gl.R32F;
  16931. case Engine.TEXTUREFORMAT_RG:
  16932. return this._gl.RG32F;
  16933. case Engine.TEXTUREFORMAT_RGB:
  16934. return this._gl.RGB32F;
  16935. }
  16936. }
  16937. return this._gl.RGBA32F;
  16938. }
  16939. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16940. if (format) {
  16941. switch (format) {
  16942. case Engine.TEXTUREFORMAT_R:
  16943. return this._gl.R16F;
  16944. case Engine.TEXTUREFORMAT_RG:
  16945. return this._gl.RG16F;
  16946. case Engine.TEXTUREFORMAT_RGB:
  16947. return this._gl.RGB16F;
  16948. }
  16949. }
  16950. return this._gl.RGBA16F;
  16951. }
  16952. if (format !== undefined) {
  16953. switch (format) {
  16954. case Engine.TEXTUREFORMAT_LUMINANCE:
  16955. return this._gl.LUMINANCE;
  16956. case Engine.TEXTUREFORMAT_RGB:
  16957. return this._gl.RGB;
  16958. case Engine.TEXTUREFORMAT_R:
  16959. return this._gl.R8;
  16960. case Engine.TEXTUREFORMAT_RG:
  16961. return this._gl.RG8;
  16962. case Engine.TEXTUREFORMAT_ALPHA:
  16963. return this._gl.ALPHA;
  16964. }
  16965. }
  16966. return this._gl.RGBA;
  16967. };
  16968. ;
  16969. /** @hidden */
  16970. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16971. if (type === Engine.TEXTURETYPE_FLOAT) {
  16972. return this._gl.RGBA32F;
  16973. }
  16974. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16975. return this._gl.RGBA16F;
  16976. }
  16977. return this._gl.RGBA8;
  16978. };
  16979. ;
  16980. /**
  16981. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16982. * @return the new query
  16983. */
  16984. Engine.prototype.createQuery = function () {
  16985. return this._gl.createQuery();
  16986. };
  16987. /**
  16988. * Delete and release a webGL query
  16989. * @param query defines the query to delete
  16990. * @return the current engine
  16991. */
  16992. Engine.prototype.deleteQuery = function (query) {
  16993. this._gl.deleteQuery(query);
  16994. return this;
  16995. };
  16996. /**
  16997. * Check if a given query has resolved and got its value
  16998. * @param query defines the query to check
  16999. * @returns true if the query got its value
  17000. */
  17001. Engine.prototype.isQueryResultAvailable = function (query) {
  17002. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17003. };
  17004. /**
  17005. * Gets the value of a given query
  17006. * @param query defines the query to check
  17007. * @returns the value of the query
  17008. */
  17009. Engine.prototype.getQueryResult = function (query) {
  17010. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17011. };
  17012. /**
  17013. * Initiates an occlusion query
  17014. * @param algorithmType defines the algorithm to use
  17015. * @param query defines the query to use
  17016. * @returns the current engine
  17017. * @see http://doc.babylonjs.com/features/occlusionquery
  17018. */
  17019. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17020. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17021. this._gl.beginQuery(glAlgorithm, query);
  17022. return this;
  17023. };
  17024. /**
  17025. * Ends an occlusion query
  17026. * @see http://doc.babylonjs.com/features/occlusionquery
  17027. * @param algorithmType defines the algorithm to use
  17028. * @returns the current engine
  17029. */
  17030. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17031. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17032. this._gl.endQuery(glAlgorithm);
  17033. return this;
  17034. };
  17035. /* Time queries */
  17036. Engine.prototype._createTimeQuery = function () {
  17037. var timerQuery = this._caps.timerQuery;
  17038. if (timerQuery.createQueryEXT) {
  17039. return timerQuery.createQueryEXT();
  17040. }
  17041. return this.createQuery();
  17042. };
  17043. Engine.prototype._deleteTimeQuery = function (query) {
  17044. var timerQuery = this._caps.timerQuery;
  17045. if (timerQuery.deleteQueryEXT) {
  17046. timerQuery.deleteQueryEXT(query);
  17047. return;
  17048. }
  17049. this.deleteQuery(query);
  17050. };
  17051. Engine.prototype._getTimeQueryResult = function (query) {
  17052. var timerQuery = this._caps.timerQuery;
  17053. if (timerQuery.getQueryObjectEXT) {
  17054. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17055. }
  17056. return this.getQueryResult(query);
  17057. };
  17058. Engine.prototype._getTimeQueryAvailability = function (query) {
  17059. var timerQuery = this._caps.timerQuery;
  17060. if (timerQuery.getQueryObjectEXT) {
  17061. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17062. }
  17063. return this.isQueryResultAvailable(query);
  17064. };
  17065. /**
  17066. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17067. * Please note that only one query can be issued at a time
  17068. * @returns a time token used to track the time span
  17069. */
  17070. Engine.prototype.startTimeQuery = function () {
  17071. var timerQuery = this._caps.timerQuery;
  17072. if (!timerQuery) {
  17073. return null;
  17074. }
  17075. var token = new BABYLON._TimeToken();
  17076. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17077. if (this._caps.canUseTimestampForTimerQuery) {
  17078. token._startTimeQuery = this._createTimeQuery();
  17079. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17080. }
  17081. else {
  17082. if (this._currentNonTimestampToken) {
  17083. return this._currentNonTimestampToken;
  17084. }
  17085. token._timeElapsedQuery = this._createTimeQuery();
  17086. if (timerQuery.beginQueryEXT) {
  17087. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17088. }
  17089. else {
  17090. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17091. }
  17092. this._currentNonTimestampToken = token;
  17093. }
  17094. return token;
  17095. };
  17096. /**
  17097. * Ends a time query
  17098. * @param token defines the token used to measure the time span
  17099. * @returns the time spent (in ns)
  17100. */
  17101. Engine.prototype.endTimeQuery = function (token) {
  17102. var timerQuery = this._caps.timerQuery;
  17103. if (!timerQuery || !token) {
  17104. return -1;
  17105. }
  17106. if (this._caps.canUseTimestampForTimerQuery) {
  17107. if (!token._startTimeQuery) {
  17108. return -1;
  17109. }
  17110. if (!token._endTimeQuery) {
  17111. token._endTimeQuery = this._createTimeQuery();
  17112. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17113. }
  17114. }
  17115. else if (!token._timeElapsedQueryEnded) {
  17116. if (!token._timeElapsedQuery) {
  17117. return -1;
  17118. }
  17119. if (timerQuery.endQueryEXT) {
  17120. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17121. }
  17122. else {
  17123. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17124. }
  17125. token._timeElapsedQueryEnded = true;
  17126. }
  17127. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17128. var available = false;
  17129. if (token._endTimeQuery) {
  17130. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17131. }
  17132. else if (token._timeElapsedQuery) {
  17133. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17134. }
  17135. if (available && !disjoint) {
  17136. var result = 0;
  17137. if (this._caps.canUseTimestampForTimerQuery) {
  17138. if (!token._startTimeQuery || !token._endTimeQuery) {
  17139. return -1;
  17140. }
  17141. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17142. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17143. result = timeEnd - timeStart;
  17144. this._deleteTimeQuery(token._startTimeQuery);
  17145. this._deleteTimeQuery(token._endTimeQuery);
  17146. token._startTimeQuery = null;
  17147. token._endTimeQuery = null;
  17148. }
  17149. else {
  17150. if (!token._timeElapsedQuery) {
  17151. return -1;
  17152. }
  17153. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17154. this._deleteTimeQuery(token._timeElapsedQuery);
  17155. token._timeElapsedQuery = null;
  17156. token._timeElapsedQueryEnded = false;
  17157. this._currentNonTimestampToken = null;
  17158. }
  17159. return result;
  17160. }
  17161. return -1;
  17162. };
  17163. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17164. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17165. };
  17166. // Transform feedback
  17167. /**
  17168. * Creates a webGL transform feedback object
  17169. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17170. * @returns the webGL transform feedback object
  17171. */
  17172. Engine.prototype.createTransformFeedback = function () {
  17173. return this._gl.createTransformFeedback();
  17174. };
  17175. /**
  17176. * Delete a webGL transform feedback object
  17177. * @param value defines the webGL transform feedback object to delete
  17178. */
  17179. Engine.prototype.deleteTransformFeedback = function (value) {
  17180. this._gl.deleteTransformFeedback(value);
  17181. };
  17182. /**
  17183. * Bind a webGL transform feedback object to the webgl context
  17184. * @param value defines the webGL transform feedback object to bind
  17185. */
  17186. Engine.prototype.bindTransformFeedback = function (value) {
  17187. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17188. };
  17189. /**
  17190. * Begins a transform feedback operation
  17191. * @param usePoints defines if points or triangles must be used
  17192. */
  17193. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17194. if (usePoints === void 0) { usePoints = true; }
  17195. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17196. };
  17197. /**
  17198. * Ends a transform feedback operation
  17199. */
  17200. Engine.prototype.endTransformFeedback = function () {
  17201. this._gl.endTransformFeedback();
  17202. };
  17203. /**
  17204. * Specify the varyings to use with transform feedback
  17205. * @param program defines the associated webGL program
  17206. * @param value defines the list of strings representing the varying names
  17207. */
  17208. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17209. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17210. };
  17211. /**
  17212. * Bind a webGL buffer for a transform feedback operation
  17213. * @param value defines the webGL buffer to bind
  17214. */
  17215. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17216. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17217. };
  17218. /** @hidden */
  17219. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17220. var _this = this;
  17221. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17222. this._activeRequests.push(request);
  17223. request.onCompleteObservable.add(function (request) {
  17224. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17225. });
  17226. return request;
  17227. };
  17228. /** @hidden */
  17229. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17230. var _this = this;
  17231. return new Promise(function (resolve, reject) {
  17232. _this._loadFile(url, function (data) {
  17233. resolve(data);
  17234. }, undefined, database, useArrayBuffer, function (request, exception) {
  17235. reject(exception);
  17236. });
  17237. });
  17238. };
  17239. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17240. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17241. var onload = function (data) {
  17242. loadedFiles[index] = data;
  17243. loadedFiles._internalCount++;
  17244. if (loadedFiles._internalCount === 6) {
  17245. onfinish(loadedFiles);
  17246. }
  17247. };
  17248. var onerror = function (request, exception) {
  17249. if (onErrorCallBack && request) {
  17250. onErrorCallBack(request.status + " " + request.statusText, exception);
  17251. }
  17252. };
  17253. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17254. };
  17255. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17256. if (onError === void 0) { onError = null; }
  17257. var loadedFiles = [];
  17258. loadedFiles._internalCount = 0;
  17259. for (var index = 0; index < 6; index++) {
  17260. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17261. }
  17262. };
  17263. // Statics
  17264. /**
  17265. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17266. * @returns true if the engine can be created
  17267. * @ignorenaming
  17268. */
  17269. Engine.isSupported = function () {
  17270. try {
  17271. var tempcanvas = document.createElement("canvas");
  17272. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17273. return gl != null && !!window.WebGLRenderingContext;
  17274. }
  17275. catch (e) {
  17276. return false;
  17277. }
  17278. };
  17279. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17280. Engine.ExceptionList = [
  17281. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17282. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17283. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17284. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17285. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17286. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17287. ];
  17288. /** Gets the list of created engines */
  17289. Engine.Instances = new Array();
  17290. // Const statics
  17291. /** Defines that alpha blending is disabled */
  17292. Engine.ALPHA_DISABLE = 0;
  17293. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17294. Engine.ALPHA_ADD = 1;
  17295. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17296. Engine.ALPHA_COMBINE = 2;
  17297. /** Defines that alpha blending to DEST - SRC * DEST */
  17298. Engine.ALPHA_SUBTRACT = 3;
  17299. /** Defines that alpha blending to SRC * DEST */
  17300. Engine.ALPHA_MULTIPLY = 4;
  17301. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17302. Engine.ALPHA_MAXIMIZED = 5;
  17303. /** Defines that alpha blending to SRC + DEST */
  17304. Engine.ALPHA_ONEONE = 6;
  17305. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17306. Engine.ALPHA_PREMULTIPLIED = 7;
  17307. /**
  17308. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17309. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17310. */
  17311. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17312. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17313. Engine.ALPHA_INTERPOLATE = 9;
  17314. /**
  17315. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17316. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17317. */
  17318. Engine.ALPHA_SCREENMODE = 10;
  17319. /** Defines that the ressource is not delayed*/
  17320. Engine.DELAYLOADSTATE_NONE = 0;
  17321. /** Defines that the ressource was successfully delay loaded */
  17322. Engine.DELAYLOADSTATE_LOADED = 1;
  17323. /** Defines that the ressource is currently delay loading */
  17324. Engine.DELAYLOADSTATE_LOADING = 2;
  17325. /** Defines that the ressource is delayed and has not started loading */
  17326. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17327. // Depht or Stencil test Constants.
  17328. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17329. Engine.NEVER = 0x0200;
  17330. /** 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 */
  17331. Engine.ALWAYS = 0x0207;
  17332. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17333. Engine.LESS = 0x0201;
  17334. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17335. Engine.EQUAL = 0x0202;
  17336. /** 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 */
  17337. Engine.LEQUAL = 0x0203;
  17338. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17339. Engine.GREATER = 0x0204;
  17340. /** 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 */
  17341. Engine.GEQUAL = 0x0206;
  17342. /** 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 */
  17343. Engine.NOTEQUAL = 0x0205;
  17344. // Stencil Actions Constants.
  17345. /** Passed to stencilOperation to specify that stencil value must be kept */
  17346. Engine.KEEP = 0x1E00;
  17347. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17348. Engine.REPLACE = 0x1E01;
  17349. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17350. Engine.INCR = 0x1E02;
  17351. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17352. Engine.DECR = 0x1E03;
  17353. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17354. Engine.INVERT = 0x150A;
  17355. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17356. Engine.INCR_WRAP = 0x8507;
  17357. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17358. Engine.DECR_WRAP = 0x8508;
  17359. /** Texture is not repeating outside of 0..1 UVs */
  17360. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17361. /** Texture is repeating outside of 0..1 UVs */
  17362. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17363. /** Texture is repeating and mirrored */
  17364. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17365. /** ALPHA */
  17366. Engine.TEXTUREFORMAT_ALPHA = 0;
  17367. /** LUMINANCE */
  17368. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17369. /** LUMINANCE_ALPHA */
  17370. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17371. /** RGB */
  17372. Engine.TEXTUREFORMAT_RGB = 4;
  17373. /** RGBA */
  17374. Engine.TEXTUREFORMAT_RGBA = 5;
  17375. /** R */
  17376. Engine.TEXTUREFORMAT_R = 6;
  17377. /** RG */
  17378. Engine.TEXTUREFORMAT_RG = 7;
  17379. /** UNSIGNED_INT */
  17380. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17381. /** FLOAT */
  17382. Engine.TEXTURETYPE_FLOAT = 1;
  17383. /** HALF_FLOAT */
  17384. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17385. /** nearest is mag = nearest and min = nearest and mip = linear */
  17386. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17387. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17388. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17389. /** Trilinear is mag = linear and min = linear and mip = linear */
  17390. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17391. /** nearest is mag = nearest and min = nearest and mip = linear */
  17392. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17393. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17394. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17395. /** Trilinear is mag = linear and min = linear and mip = linear */
  17396. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17397. /** mag = nearest and min = nearest and mip = nearest */
  17398. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17399. /** mag = nearest and min = linear and mip = nearest */
  17400. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17401. /** mag = nearest and min = linear and mip = linear */
  17402. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17403. /** mag = nearest and min = linear and mip = none */
  17404. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17405. /** mag = nearest and min = nearest and mip = none */
  17406. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17407. /** mag = linear and min = nearest and mip = nearest */
  17408. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17409. /** mag = linear and min = nearest and mip = linear */
  17410. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17411. /** mag = linear and min = linear and mip = none */
  17412. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17413. /** mag = linear and min = nearest and mip = none */
  17414. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17415. /** Explicit coordinates mode */
  17416. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17417. /** Spherical coordinates mode */
  17418. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17419. /** Planar coordinates mode */
  17420. Engine.TEXTURE_PLANAR_MODE = 2;
  17421. /** Cubic coordinates mode */
  17422. Engine.TEXTURE_CUBIC_MODE = 3;
  17423. /** Projection coordinates mode */
  17424. Engine.TEXTURE_PROJECTION_MODE = 4;
  17425. /** Skybox coordinates mode */
  17426. Engine.TEXTURE_SKYBOX_MODE = 5;
  17427. /** Inverse Cubic coordinates mode */
  17428. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17429. /** Equirectangular coordinates mode */
  17430. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17431. /** Equirectangular Fixed coordinates mode */
  17432. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17433. /** Equirectangular Fixed Mirrored coordinates mode */
  17434. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17435. // Texture rescaling mode
  17436. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17437. Engine.SCALEMODE_FLOOR = 1;
  17438. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17439. Engine.SCALEMODE_NEAREST = 2;
  17440. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17441. Engine.SCALEMODE_CEILING = 3;
  17442. // Updatable statics so stick with vars here
  17443. /**
  17444. * Gets or sets the epsilon value used by collision engine
  17445. */
  17446. Engine.CollisionsEpsilon = 0.001;
  17447. /**
  17448. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17449. */
  17450. Engine.CodeRepository = "src/";
  17451. /**
  17452. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17453. */
  17454. Engine.ShadersRepository = "src/Shaders/";
  17455. return Engine;
  17456. }());
  17457. BABYLON.Engine = Engine;
  17458. })(BABYLON || (BABYLON = {}));
  17459. //# sourceMappingURL=babylon.engine.js.map
  17460. var BABYLON;
  17461. (function (BABYLON) {
  17462. /**
  17463. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17464. */
  17465. var Node = /** @class */ (function () {
  17466. /**
  17467. * Creates a new Node
  17468. * @param {string} name - the name and id to be given to this node
  17469. * @param {BABYLON.Scene} the scene this node will be added to
  17470. */
  17471. function Node(name, scene) {
  17472. if (scene === void 0) { scene = null; }
  17473. /**
  17474. * Gets or sets a string used to store user defined state for the node
  17475. */
  17476. this.state = "";
  17477. /**
  17478. * Gets or sets an object used to store user defined information for the node
  17479. */
  17480. this.metadata = null;
  17481. /**
  17482. * Gets or sets a boolean used to define if the node must be serialized
  17483. */
  17484. this.doNotSerialize = false;
  17485. /** @hidden */
  17486. this._isDisposed = false;
  17487. /**
  17488. * Gets a list of Animations associated with the node
  17489. */
  17490. this.animations = new Array();
  17491. this._ranges = {};
  17492. this._isEnabled = true;
  17493. this._isReady = true;
  17494. /** @hidden */
  17495. this._currentRenderId = -1;
  17496. this._parentRenderId = -1;
  17497. this._childRenderId = -1;
  17498. this._animationPropertiesOverride = null;
  17499. /**
  17500. * An event triggered when the mesh is disposed
  17501. */
  17502. this.onDisposeObservable = new BABYLON.Observable();
  17503. // Behaviors
  17504. this._behaviors = new Array();
  17505. this.name = name;
  17506. this.id = name;
  17507. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17508. this.uniqueId = this._scene.getUniqueId();
  17509. this._initCache();
  17510. }
  17511. /**
  17512. * Add a new node constructor
  17513. * @param type defines the type name of the node to construct
  17514. * @param constructorFunc defines the constructor function
  17515. */
  17516. Node.AddNodeConstructor = function (type, constructorFunc) {
  17517. this._NodeConstructors[type] = constructorFunc;
  17518. };
  17519. /**
  17520. * Returns a node constructor based on type name
  17521. * @param type defines the type name
  17522. * @param name defines the new node name
  17523. * @param scene defines the hosting scene
  17524. * @param options defines optional options to transmit to constructors
  17525. * @returns the new constructor or null
  17526. */
  17527. Node.Construct = function (type, name, scene, options) {
  17528. var constructorFunc = this._NodeConstructors[type];
  17529. if (!constructorFunc) {
  17530. return null;
  17531. }
  17532. return constructorFunc(name, scene, options);
  17533. };
  17534. /**
  17535. * Gets a boolean indicating if the node has been disposed
  17536. * @returns true if the node was disposed
  17537. */
  17538. Node.prototype.isDisposed = function () {
  17539. return this._isDisposed;
  17540. };
  17541. Object.defineProperty(Node.prototype, "parent", {
  17542. get: function () {
  17543. return this._parentNode;
  17544. },
  17545. /**
  17546. * Gets or sets the parent of the node
  17547. */
  17548. set: function (parent) {
  17549. if (this._parentNode === parent) {
  17550. return;
  17551. }
  17552. // Remove self from list of children of parent
  17553. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17554. var index = this._parentNode._children.indexOf(this);
  17555. if (index !== -1) {
  17556. this._parentNode._children.splice(index, 1);
  17557. }
  17558. }
  17559. // Store new parent
  17560. this._parentNode = parent;
  17561. // Add as child to new parent
  17562. if (this._parentNode) {
  17563. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17564. this._parentNode._children = new Array();
  17565. }
  17566. this._parentNode._children.push(this);
  17567. }
  17568. },
  17569. enumerable: true,
  17570. configurable: true
  17571. });
  17572. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17573. /**
  17574. * Gets or sets the animation properties override
  17575. */
  17576. get: function () {
  17577. if (!this._animationPropertiesOverride) {
  17578. return this._scene.animationPropertiesOverride;
  17579. }
  17580. return this._animationPropertiesOverride;
  17581. },
  17582. set: function (value) {
  17583. this._animationPropertiesOverride = value;
  17584. },
  17585. enumerable: true,
  17586. configurable: true
  17587. });
  17588. /**
  17589. * Gets a string idenfifying the name of the class
  17590. * @returns "Node" string
  17591. */
  17592. Node.prototype.getClassName = function () {
  17593. return "Node";
  17594. };
  17595. Object.defineProperty(Node.prototype, "onDispose", {
  17596. /**
  17597. * Sets a callback that will be raised when the node will be disposed
  17598. */
  17599. set: function (callback) {
  17600. if (this._onDisposeObserver) {
  17601. this.onDisposeObservable.remove(this._onDisposeObserver);
  17602. }
  17603. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17604. },
  17605. enumerable: true,
  17606. configurable: true
  17607. });
  17608. /**
  17609. * Gets the scene of the node
  17610. * @returns a {BABYLON.Scene}
  17611. */
  17612. Node.prototype.getScene = function () {
  17613. return this._scene;
  17614. };
  17615. /**
  17616. * Gets the engine of the node
  17617. * @returns a {BABYLON.Engine}
  17618. */
  17619. Node.prototype.getEngine = function () {
  17620. return this._scene.getEngine();
  17621. };
  17622. /**
  17623. * Attach a behavior to the node
  17624. * @see http://doc.babylonjs.com/features/behaviour
  17625. * @param behavior defines the behavior to attach
  17626. * @returns the current Node
  17627. */
  17628. Node.prototype.addBehavior = function (behavior) {
  17629. var _this = this;
  17630. var index = this._behaviors.indexOf(behavior);
  17631. if (index !== -1) {
  17632. return this;
  17633. }
  17634. behavior.init();
  17635. if (this._scene.isLoading) {
  17636. // We defer the attach when the scene will be loaded
  17637. this._scene.onDataLoadedObservable.addOnce(function () {
  17638. behavior.attach(_this);
  17639. });
  17640. }
  17641. else {
  17642. behavior.attach(this);
  17643. }
  17644. this._behaviors.push(behavior);
  17645. return this;
  17646. };
  17647. /**
  17648. * Remove an attached behavior
  17649. * @see http://doc.babylonjs.com/features/behaviour
  17650. * @param behavior defines the behavior to attach
  17651. * @returns the current Node
  17652. */
  17653. Node.prototype.removeBehavior = function (behavior) {
  17654. var index = this._behaviors.indexOf(behavior);
  17655. if (index === -1) {
  17656. return this;
  17657. }
  17658. this._behaviors[index].detach();
  17659. this._behaviors.splice(index, 1);
  17660. return this;
  17661. };
  17662. Object.defineProperty(Node.prototype, "behaviors", {
  17663. /**
  17664. * Gets the list of attached behaviors
  17665. * @see http://doc.babylonjs.com/features/behaviour
  17666. */
  17667. get: function () {
  17668. return this._behaviors;
  17669. },
  17670. enumerable: true,
  17671. configurable: true
  17672. });
  17673. /**
  17674. * Gets an attached behavior by name
  17675. * @param name defines the name of the behavior to look for
  17676. * @see http://doc.babylonjs.com/features/behaviour
  17677. * @returns null if behavior was not found else the requested behavior
  17678. */
  17679. Node.prototype.getBehaviorByName = function (name) {
  17680. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17681. var behavior = _a[_i];
  17682. if (behavior.name === name) {
  17683. return behavior;
  17684. }
  17685. }
  17686. return null;
  17687. };
  17688. /**
  17689. * Returns the world matrix of the node
  17690. * @returns a matrix containing the node's world matrix
  17691. */
  17692. Node.prototype.getWorldMatrix = function () {
  17693. return BABYLON.Matrix.Identity();
  17694. };
  17695. /** @hidden */
  17696. Node.prototype._getWorldMatrixDeterminant = function () {
  17697. return 1;
  17698. };
  17699. // override it in derived class if you add new variables to the cache
  17700. // and call the parent class method
  17701. /** @hidden */
  17702. Node.prototype._initCache = function () {
  17703. this._cache = {};
  17704. this._cache.parent = undefined;
  17705. };
  17706. /** @hidden */
  17707. Node.prototype.updateCache = function (force) {
  17708. if (!force && this.isSynchronized())
  17709. return;
  17710. this._cache.parent = this.parent;
  17711. this._updateCache();
  17712. };
  17713. // override it in derived class if you add new variables to the cache
  17714. // and call the parent class method if !ignoreParentClass
  17715. /** @hidden */
  17716. Node.prototype._updateCache = function (ignoreParentClass) {
  17717. };
  17718. // override it in derived class if you add new variables to the cache
  17719. /** @hidden */
  17720. Node.prototype._isSynchronized = function () {
  17721. return true;
  17722. };
  17723. /** @hidden */
  17724. Node.prototype._markSyncedWithParent = function () {
  17725. if (this.parent) {
  17726. this._parentRenderId = this.parent._childRenderId;
  17727. }
  17728. };
  17729. /** @hidden */
  17730. Node.prototype.isSynchronizedWithParent = function () {
  17731. if (!this.parent) {
  17732. return true;
  17733. }
  17734. if (this._parentRenderId !== this.parent._childRenderId) {
  17735. return false;
  17736. }
  17737. return this.parent.isSynchronized();
  17738. };
  17739. /** @hidden */
  17740. Node.prototype.isSynchronized = function (updateCache) {
  17741. var check = this.hasNewParent();
  17742. check = check || !this.isSynchronizedWithParent();
  17743. check = check || !this._isSynchronized();
  17744. if (updateCache)
  17745. this.updateCache(true);
  17746. return !check;
  17747. };
  17748. /** @hidden */
  17749. Node.prototype.hasNewParent = function (update) {
  17750. if (this._cache.parent === this.parent)
  17751. return false;
  17752. if (update)
  17753. this._cache.parent = this.parent;
  17754. return true;
  17755. };
  17756. /**
  17757. * Is this node ready to be used/rendered
  17758. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17759. * @return true if the node is ready
  17760. */
  17761. Node.prototype.isReady = function (completeCheck) {
  17762. if (completeCheck === void 0) { completeCheck = false; }
  17763. return this._isReady;
  17764. };
  17765. /**
  17766. * Is this node enabled?
  17767. * 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
  17768. * @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
  17769. * @return whether this node (and its parent) is enabled
  17770. */
  17771. Node.prototype.isEnabled = function (checkAncestors) {
  17772. if (checkAncestors === void 0) { checkAncestors = true; }
  17773. if (checkAncestors === false) {
  17774. return this._isEnabled;
  17775. }
  17776. if (this._isEnabled === false) {
  17777. return false;
  17778. }
  17779. if (this.parent !== undefined && this.parent !== null) {
  17780. return this.parent.isEnabled(checkAncestors);
  17781. }
  17782. return true;
  17783. };
  17784. /**
  17785. * Set the enabled state of this node
  17786. * @param value defines the new enabled state
  17787. */
  17788. Node.prototype.setEnabled = function (value) {
  17789. this._isEnabled = value;
  17790. };
  17791. /**
  17792. * Is this node a descendant of the given node?
  17793. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17794. * @param ancestor defines the parent node to inspect
  17795. * @returns a boolean indicating if this node is a descendant of the given node
  17796. */
  17797. Node.prototype.isDescendantOf = function (ancestor) {
  17798. if (this.parent) {
  17799. if (this.parent === ancestor) {
  17800. return true;
  17801. }
  17802. return this.parent.isDescendantOf(ancestor);
  17803. }
  17804. return false;
  17805. };
  17806. /** @hidden */
  17807. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17808. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17809. if (!this._children) {
  17810. return;
  17811. }
  17812. for (var index = 0; index < this._children.length; index++) {
  17813. var item = this._children[index];
  17814. if (!predicate || predicate(item)) {
  17815. results.push(item);
  17816. }
  17817. if (!directDescendantsOnly) {
  17818. item._getDescendants(results, false, predicate);
  17819. }
  17820. }
  17821. };
  17822. /**
  17823. * Will return all nodes that have this node as ascendant
  17824. * @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
  17825. * @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
  17826. * @return all children nodes of all types
  17827. */
  17828. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17829. var results = new Array();
  17830. this._getDescendants(results, directDescendantsOnly, predicate);
  17831. return results;
  17832. };
  17833. /**
  17834. * Get all child-meshes of this node
  17835. * @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
  17836. * @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
  17837. * @returns an array of {BABYLON.AbstractMesh}
  17838. */
  17839. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17840. var results = [];
  17841. this._getDescendants(results, directDescendantsOnly, function (node) {
  17842. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17843. });
  17844. return results;
  17845. };
  17846. /**
  17847. * Get all child-transformNodes of this node
  17848. * @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
  17849. * @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
  17850. * @returns an array of {BABYLON.TransformNode}
  17851. */
  17852. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17853. var results = [];
  17854. this._getDescendants(results, directDescendantsOnly, function (node) {
  17855. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17856. });
  17857. return results;
  17858. };
  17859. /**
  17860. * Get all direct children of this node
  17861. * @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
  17862. * @returns an array of {BABYLON.Node}
  17863. */
  17864. Node.prototype.getChildren = function (predicate) {
  17865. return this.getDescendants(true, predicate);
  17866. };
  17867. /** @hidden */
  17868. Node.prototype._setReady = function (state) {
  17869. if (state === this._isReady) {
  17870. return;
  17871. }
  17872. if (!state) {
  17873. this._isReady = false;
  17874. return;
  17875. }
  17876. if (this.onReady) {
  17877. this.onReady(this);
  17878. }
  17879. this._isReady = true;
  17880. };
  17881. /**
  17882. * Get an animation by name
  17883. * @param name defines the name of the animation to look for
  17884. * @returns null if not found else the requested animation
  17885. */
  17886. Node.prototype.getAnimationByName = function (name) {
  17887. for (var i = 0; i < this.animations.length; i++) {
  17888. var animation = this.animations[i];
  17889. if (animation.name === name) {
  17890. return animation;
  17891. }
  17892. }
  17893. return null;
  17894. };
  17895. /**
  17896. * Creates an animation range for this node
  17897. * @param name defines the name of the range
  17898. * @param from defines the starting key
  17899. * @param to defines the end key
  17900. */
  17901. Node.prototype.createAnimationRange = function (name, from, to) {
  17902. // check name not already in use
  17903. if (!this._ranges[name]) {
  17904. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17905. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17906. if (this.animations[i]) {
  17907. this.animations[i].createRange(name, from, to);
  17908. }
  17909. }
  17910. }
  17911. };
  17912. /**
  17913. * Delete a specific animation range
  17914. * @param name defines the name of the range to delete
  17915. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17916. */
  17917. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17918. if (deleteFrames === void 0) { deleteFrames = true; }
  17919. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17920. if (this.animations[i]) {
  17921. this.animations[i].deleteRange(name, deleteFrames);
  17922. }
  17923. }
  17924. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17925. };
  17926. /**
  17927. * Get an animation range by name
  17928. * @param name defines the name of the animation range to look for
  17929. * @returns null if not found else the requested animation range
  17930. */
  17931. Node.prototype.getAnimationRange = function (name) {
  17932. return this._ranges[name];
  17933. };
  17934. /**
  17935. * Will start the animation sequence
  17936. * @param name defines the range frames for animation sequence
  17937. * @param loop defines if the animation should loop (false by default)
  17938. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17939. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17940. * @returns the object created for this animation. If range does not exist, it will return null
  17941. */
  17942. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17943. var range = this.getAnimationRange(name);
  17944. if (!range) {
  17945. return null;
  17946. }
  17947. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17948. };
  17949. /**
  17950. * Serialize animation ranges into a JSON compatible object
  17951. * @returns serialization object
  17952. */
  17953. Node.prototype.serializeAnimationRanges = function () {
  17954. var serializationRanges = [];
  17955. for (var name in this._ranges) {
  17956. var localRange = this._ranges[name];
  17957. if (!localRange) {
  17958. continue;
  17959. }
  17960. var range = {};
  17961. range.name = name;
  17962. range.from = localRange.from;
  17963. range.to = localRange.to;
  17964. serializationRanges.push(range);
  17965. }
  17966. return serializationRanges;
  17967. };
  17968. /**
  17969. * Computes the world matrix of the node
  17970. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17971. * @returns the world matrix
  17972. */
  17973. Node.prototype.computeWorldMatrix = function (force) {
  17974. return BABYLON.Matrix.Identity();
  17975. };
  17976. /**
  17977. * Releases resources associated with this node.
  17978. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17979. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17980. */
  17981. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17982. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17983. if (!doNotRecurse) {
  17984. var nodes = this.getDescendants(true);
  17985. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17986. var node = nodes_1[_i];
  17987. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17988. }
  17989. }
  17990. else {
  17991. var transformNodes = this.getChildTransformNodes(true);
  17992. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17993. var transformNode = transformNodes_1[_a];
  17994. transformNode.parent = null;
  17995. transformNode.computeWorldMatrix(true);
  17996. }
  17997. }
  17998. this.parent = null;
  17999. // Callback
  18000. this.onDisposeObservable.notifyObservers(this);
  18001. this.onDisposeObservable.clear();
  18002. // Behaviors
  18003. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18004. var behavior = _c[_b];
  18005. behavior.detach();
  18006. }
  18007. this._behaviors = [];
  18008. this._isDisposed = true;
  18009. };
  18010. /**
  18011. * Parse animation range data from a serialization object and store them into a given node
  18012. * @param node defines where to store the animation ranges
  18013. * @param parsedNode defines the serialization object to read data from
  18014. * @param scene defines the hosting scene
  18015. */
  18016. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18017. if (parsedNode.ranges) {
  18018. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18019. var data = parsedNode.ranges[index];
  18020. node.createAnimationRange(data.name, data.from, data.to);
  18021. }
  18022. }
  18023. };
  18024. Node._NodeConstructors = {};
  18025. __decorate([
  18026. BABYLON.serialize()
  18027. ], Node.prototype, "name", void 0);
  18028. __decorate([
  18029. BABYLON.serialize()
  18030. ], Node.prototype, "id", void 0);
  18031. __decorate([
  18032. BABYLON.serialize()
  18033. ], Node.prototype, "uniqueId", void 0);
  18034. __decorate([
  18035. BABYLON.serialize()
  18036. ], Node.prototype, "state", void 0);
  18037. __decorate([
  18038. BABYLON.serialize()
  18039. ], Node.prototype, "metadata", void 0);
  18040. return Node;
  18041. }());
  18042. BABYLON.Node = Node;
  18043. })(BABYLON || (BABYLON = {}));
  18044. //# sourceMappingURL=babylon.node.js.map
  18045. var BABYLON;
  18046. (function (BABYLON) {
  18047. var BoundingSphere = /** @class */ (function () {
  18048. /**
  18049. * Creates a new bounding sphere
  18050. * @param min defines the minimum vector (in local space)
  18051. * @param max defines the maximum vector (in local space)
  18052. */
  18053. function BoundingSphere(min, max) {
  18054. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18055. this.reConstruct(min, max);
  18056. }
  18057. /**
  18058. * Recreates the entire bounding sphere from scratch
  18059. * @param min defines the new minimum vector (in local space)
  18060. * @param max defines the new maximum vector (in local space)
  18061. */
  18062. BoundingSphere.prototype.reConstruct = function (min, max) {
  18063. this.minimum = min.clone();
  18064. this.maximum = max.clone();
  18065. var distance = BABYLON.Vector3.Distance(min, max);
  18066. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18067. this.radius = distance * 0.5;
  18068. this.centerWorld = BABYLON.Vector3.Zero();
  18069. this._update(BABYLON.Matrix.Identity());
  18070. };
  18071. // Methods
  18072. BoundingSphere.prototype._update = function (world) {
  18073. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18074. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18075. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18076. };
  18077. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18078. for (var i = 0; i < 6; i++) {
  18079. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18080. return false;
  18081. }
  18082. return true;
  18083. };
  18084. BoundingSphere.prototype.intersectsPoint = function (point) {
  18085. var x = this.centerWorld.x - point.x;
  18086. var y = this.centerWorld.y - point.y;
  18087. var z = this.centerWorld.z - point.z;
  18088. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18089. if (this.radiusWorld < distance)
  18090. return false;
  18091. return true;
  18092. };
  18093. // Statics
  18094. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18095. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18096. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18097. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18098. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18099. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18100. return false;
  18101. return true;
  18102. };
  18103. return BoundingSphere;
  18104. }());
  18105. BABYLON.BoundingSphere = BoundingSphere;
  18106. })(BABYLON || (BABYLON = {}));
  18107. //# sourceMappingURL=babylon.boundingSphere.js.map
  18108. var BABYLON;
  18109. (function (BABYLON) {
  18110. var BoundingBox = /** @class */ (function () {
  18111. /**
  18112. * Creates a new bounding box
  18113. * @param min defines the minimum vector (in local space)
  18114. * @param max defines the maximum vector (in local space)
  18115. */
  18116. function BoundingBox(min, max) {
  18117. this.vectorsWorld = new Array();
  18118. this.reConstruct(min, max);
  18119. }
  18120. // Methods
  18121. /**
  18122. * Recreates the entire bounding box from scratch
  18123. * @param min defines the new minimum vector (in local space)
  18124. * @param max defines the new maximum vector (in local space)
  18125. */
  18126. BoundingBox.prototype.reConstruct = function (min, max) {
  18127. this.minimum = min.clone();
  18128. this.maximum = max.clone();
  18129. // Bounding vectors
  18130. this.vectors = new Array();
  18131. this.vectors.push(this.minimum.clone());
  18132. this.vectors.push(this.maximum.clone());
  18133. this.vectors.push(this.minimum.clone());
  18134. this.vectors[2].x = this.maximum.x;
  18135. this.vectors.push(this.minimum.clone());
  18136. this.vectors[3].y = this.maximum.y;
  18137. this.vectors.push(this.minimum.clone());
  18138. this.vectors[4].z = this.maximum.z;
  18139. this.vectors.push(this.maximum.clone());
  18140. this.vectors[5].z = this.minimum.z;
  18141. this.vectors.push(this.maximum.clone());
  18142. this.vectors[6].x = this.minimum.x;
  18143. this.vectors.push(this.maximum.clone());
  18144. this.vectors[7].y = this.minimum.y;
  18145. // OBB
  18146. this.center = this.maximum.add(this.minimum).scale(0.5);
  18147. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18148. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18149. // World
  18150. for (var index = 0; index < this.vectors.length; index++) {
  18151. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18152. }
  18153. this.minimumWorld = BABYLON.Vector3.Zero();
  18154. this.maximumWorld = BABYLON.Vector3.Zero();
  18155. this.centerWorld = BABYLON.Vector3.Zero();
  18156. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18157. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18158. };
  18159. BoundingBox.prototype.getWorldMatrix = function () {
  18160. return this._worldMatrix;
  18161. };
  18162. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18163. this._worldMatrix.copyFrom(matrix);
  18164. return this;
  18165. };
  18166. BoundingBox.prototype._update = function (world) {
  18167. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18168. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18169. for (var index = 0; index < this.vectors.length; index++) {
  18170. var v = this.vectorsWorld[index];
  18171. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18172. if (v.x < this.minimumWorld.x)
  18173. this.minimumWorld.x = v.x;
  18174. if (v.y < this.minimumWorld.y)
  18175. this.minimumWorld.y = v.y;
  18176. if (v.z < this.minimumWorld.z)
  18177. this.minimumWorld.z = v.z;
  18178. if (v.x > this.maximumWorld.x)
  18179. this.maximumWorld.x = v.x;
  18180. if (v.y > this.maximumWorld.y)
  18181. this.maximumWorld.y = v.y;
  18182. if (v.z > this.maximumWorld.z)
  18183. this.maximumWorld.z = v.z;
  18184. }
  18185. // Extend
  18186. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18187. this.extendSizeWorld.scaleInPlace(0.5);
  18188. // OBB
  18189. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18190. this.centerWorld.scaleInPlace(0.5);
  18191. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18192. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18193. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18194. this._worldMatrix = world;
  18195. };
  18196. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18197. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18198. };
  18199. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18200. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18201. };
  18202. BoundingBox.prototype.intersectsPoint = function (point) {
  18203. var delta = -BABYLON.Epsilon;
  18204. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18205. return false;
  18206. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18207. return false;
  18208. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18209. return false;
  18210. return true;
  18211. };
  18212. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18213. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18214. };
  18215. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18216. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18217. return false;
  18218. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18219. return false;
  18220. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18221. return false;
  18222. return true;
  18223. };
  18224. // Statics
  18225. BoundingBox.Intersects = function (box0, box1) {
  18226. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18227. return false;
  18228. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18229. return false;
  18230. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18231. return false;
  18232. return true;
  18233. };
  18234. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18235. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18236. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18237. return (num <= (sphereRadius * sphereRadius));
  18238. };
  18239. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18240. for (var p = 0; p < 6; p++) {
  18241. for (var i = 0; i < 8; i++) {
  18242. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18243. return false;
  18244. }
  18245. }
  18246. }
  18247. return true;
  18248. };
  18249. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18250. for (var p = 0; p < 6; p++) {
  18251. var inCount = 8;
  18252. for (var i = 0; i < 8; i++) {
  18253. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18254. --inCount;
  18255. }
  18256. else {
  18257. break;
  18258. }
  18259. }
  18260. if (inCount === 0)
  18261. return false;
  18262. }
  18263. return true;
  18264. };
  18265. return BoundingBox;
  18266. }());
  18267. BABYLON.BoundingBox = BoundingBox;
  18268. })(BABYLON || (BABYLON = {}));
  18269. //# sourceMappingURL=babylon.boundingBox.js.map
  18270. var BABYLON;
  18271. (function (BABYLON) {
  18272. var computeBoxExtents = function (axis, box) {
  18273. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18274. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18275. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18276. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18277. var r = r0 + r1 + r2;
  18278. return {
  18279. min: p - r,
  18280. max: p + r
  18281. };
  18282. };
  18283. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18284. var axisOverlap = function (axis, box0, box1) {
  18285. var result0 = computeBoxExtents(axis, box0);
  18286. var result1 = computeBoxExtents(axis, box1);
  18287. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18288. };
  18289. var BoundingInfo = /** @class */ (function () {
  18290. function BoundingInfo(minimum, maximum) {
  18291. this.minimum = minimum;
  18292. this.maximum = maximum;
  18293. this._isLocked = false;
  18294. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18295. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18296. }
  18297. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18298. get: function () {
  18299. return this._isLocked;
  18300. },
  18301. set: function (value) {
  18302. this._isLocked = value;
  18303. },
  18304. enumerable: true,
  18305. configurable: true
  18306. });
  18307. // Methods
  18308. BoundingInfo.prototype.update = function (world) {
  18309. if (this._isLocked) {
  18310. return;
  18311. }
  18312. this.boundingBox._update(world);
  18313. this.boundingSphere._update(world);
  18314. };
  18315. /**
  18316. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18317. * @param center New center of the bounding info
  18318. * @param extend New extend of the bounding info
  18319. */
  18320. BoundingInfo.prototype.centerOn = function (center, extend) {
  18321. this.minimum = center.subtract(extend);
  18322. this.maximum = center.add(extend);
  18323. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18324. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18325. return this;
  18326. };
  18327. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18328. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18329. return false;
  18330. return this.boundingBox.isInFrustum(frustumPlanes);
  18331. };
  18332. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18333. /**
  18334. * Gets the world distance between the min and max points of the bounding box
  18335. */
  18336. get: function () {
  18337. var boundingBox = this.boundingBox;
  18338. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18339. return size.length();
  18340. },
  18341. enumerable: true,
  18342. configurable: true
  18343. });
  18344. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18345. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18346. };
  18347. BoundingInfo.prototype._checkCollision = function (collider) {
  18348. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18349. };
  18350. BoundingInfo.prototype.intersectsPoint = function (point) {
  18351. if (!this.boundingSphere.centerWorld) {
  18352. return false;
  18353. }
  18354. if (!this.boundingSphere.intersectsPoint(point)) {
  18355. return false;
  18356. }
  18357. if (!this.boundingBox.intersectsPoint(point)) {
  18358. return false;
  18359. }
  18360. return true;
  18361. };
  18362. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18363. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18364. return false;
  18365. }
  18366. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18367. return false;
  18368. }
  18369. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18370. return false;
  18371. }
  18372. if (!precise) {
  18373. return true;
  18374. }
  18375. var box0 = this.boundingBox;
  18376. var box1 = boundingInfo.boundingBox;
  18377. if (!axisOverlap(box0.directions[0], box0, box1))
  18378. return false;
  18379. if (!axisOverlap(box0.directions[1], box0, box1))
  18380. return false;
  18381. if (!axisOverlap(box0.directions[2], box0, box1))
  18382. return false;
  18383. if (!axisOverlap(box1.directions[0], box0, box1))
  18384. return false;
  18385. if (!axisOverlap(box1.directions[1], box0, box1))
  18386. return false;
  18387. if (!axisOverlap(box1.directions[2], box0, box1))
  18388. return false;
  18389. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18390. return false;
  18391. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18392. return false;
  18393. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18394. return false;
  18395. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18396. return false;
  18397. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18398. return false;
  18399. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18400. return false;
  18401. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18402. return false;
  18403. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18404. return false;
  18405. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18406. return false;
  18407. return true;
  18408. };
  18409. return BoundingInfo;
  18410. }());
  18411. BABYLON.BoundingInfo = BoundingInfo;
  18412. })(BABYLON || (BABYLON = {}));
  18413. //# sourceMappingURL=babylon.boundingInfo.js.map
  18414. var BABYLON;
  18415. (function (BABYLON) {
  18416. var TransformNode = /** @class */ (function (_super) {
  18417. __extends(TransformNode, _super);
  18418. function TransformNode(name, scene, isPure) {
  18419. if (scene === void 0) { scene = null; }
  18420. if (isPure === void 0) { isPure = true; }
  18421. var _this = _super.call(this, name, scene) || this;
  18422. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18423. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18424. _this._up = new BABYLON.Vector3(0, 1, 0);
  18425. _this._right = new BABYLON.Vector3(1, 0, 0);
  18426. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18427. // Properties
  18428. _this._rotation = BABYLON.Vector3.Zero();
  18429. _this._scaling = BABYLON.Vector3.One();
  18430. _this._isDirty = false;
  18431. /**
  18432. * Set the billboard mode. Default is 0.
  18433. *
  18434. * | Value | Type | Description |
  18435. * | --- | --- | --- |
  18436. * | 0 | BILLBOARDMODE_NONE | |
  18437. * | 1 | BILLBOARDMODE_X | |
  18438. * | 2 | BILLBOARDMODE_Y | |
  18439. * | 4 | BILLBOARDMODE_Z | |
  18440. * | 7 | BILLBOARDMODE_ALL | |
  18441. *
  18442. */
  18443. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18444. _this.scalingDeterminant = 1;
  18445. _this.infiniteDistance = false;
  18446. /**
  18447. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18448. * By default the system will update normals to compensate
  18449. */
  18450. _this.ignoreNonUniformScaling = false;
  18451. _this.position = BABYLON.Vector3.Zero();
  18452. _this._localWorld = BABYLON.Matrix.Zero();
  18453. _this._worldMatrix = BABYLON.Matrix.Zero();
  18454. _this._worldMatrixDeterminant = 0;
  18455. _this._absolutePosition = BABYLON.Vector3.Zero();
  18456. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18457. _this._postMultiplyPivotMatrix = false;
  18458. _this._isWorldMatrixFrozen = false;
  18459. /**
  18460. * An event triggered after the world matrix is updated
  18461. */
  18462. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18463. _this._nonUniformScaling = false;
  18464. if (isPure) {
  18465. _this.getScene().addTransformNode(_this);
  18466. }
  18467. return _this;
  18468. }
  18469. /**
  18470. * Gets a string idenfifying the name of the class
  18471. * @returns "TransformNode" string
  18472. */
  18473. TransformNode.prototype.getClassName = function () {
  18474. return "TransformNode";
  18475. };
  18476. Object.defineProperty(TransformNode.prototype, "rotation", {
  18477. /**
  18478. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18479. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18480. * Default : (0.0, 0.0, 0.0)
  18481. */
  18482. get: function () {
  18483. return this._rotation;
  18484. },
  18485. set: function (newRotation) {
  18486. this._rotation = newRotation;
  18487. },
  18488. enumerable: true,
  18489. configurable: true
  18490. });
  18491. Object.defineProperty(TransformNode.prototype, "scaling", {
  18492. /**
  18493. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18494. * Default : (1.0, 1.0, 1.0)
  18495. */
  18496. get: function () {
  18497. return this._scaling;
  18498. },
  18499. /**
  18500. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18501. * Default : (1.0, 1.0, 1.0)
  18502. */
  18503. set: function (newScaling) {
  18504. this._scaling = newScaling;
  18505. },
  18506. enumerable: true,
  18507. configurable: true
  18508. });
  18509. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18510. /**
  18511. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18512. * It's null by default.
  18513. * 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)
  18514. */
  18515. get: function () {
  18516. return this._rotationQuaternion;
  18517. },
  18518. set: function (quaternion) {
  18519. this._rotationQuaternion = quaternion;
  18520. //reset the rotation vector.
  18521. if (quaternion && this.rotation.length()) {
  18522. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18523. }
  18524. },
  18525. enumerable: true,
  18526. configurable: true
  18527. });
  18528. Object.defineProperty(TransformNode.prototype, "forward", {
  18529. /**
  18530. * The forward direction of that transform in world space.
  18531. */
  18532. get: function () {
  18533. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18534. },
  18535. enumerable: true,
  18536. configurable: true
  18537. });
  18538. Object.defineProperty(TransformNode.prototype, "up", {
  18539. /**
  18540. * The up direction of that transform in world space.
  18541. */
  18542. get: function () {
  18543. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18544. },
  18545. enumerable: true,
  18546. configurable: true
  18547. });
  18548. Object.defineProperty(TransformNode.prototype, "right", {
  18549. /**
  18550. * The right direction of that transform in world space.
  18551. */
  18552. get: function () {
  18553. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18554. },
  18555. enumerable: true,
  18556. configurable: true
  18557. });
  18558. /**
  18559. * Returns the latest update of the World matrix
  18560. * Returns a Matrix.
  18561. */
  18562. TransformNode.prototype.getWorldMatrix = function () {
  18563. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18564. this.computeWorldMatrix();
  18565. }
  18566. return this._worldMatrix;
  18567. };
  18568. /** @hidden */
  18569. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18570. return this._worldMatrixDeterminant;
  18571. };
  18572. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18573. /**
  18574. * Returns directly the latest state of the mesh World matrix.
  18575. * A Matrix is returned.
  18576. */
  18577. get: function () {
  18578. return this._worldMatrix;
  18579. },
  18580. enumerable: true,
  18581. configurable: true
  18582. });
  18583. /**
  18584. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18585. * Returns the TransformNode.
  18586. */
  18587. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18588. this._poseMatrix.copyFrom(matrix);
  18589. return this;
  18590. };
  18591. /**
  18592. * Returns the mesh Pose matrix.
  18593. * Returned object : Matrix
  18594. */
  18595. TransformNode.prototype.getPoseMatrix = function () {
  18596. return this._poseMatrix;
  18597. };
  18598. TransformNode.prototype._isSynchronized = function () {
  18599. if (this._isDirty) {
  18600. return false;
  18601. }
  18602. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18603. return false;
  18604. if (this._cache.pivotMatrixUpdated) {
  18605. return false;
  18606. }
  18607. if (this.infiniteDistance) {
  18608. return false;
  18609. }
  18610. if (!this._cache.position.equals(this.position))
  18611. return false;
  18612. if (this.rotationQuaternion) {
  18613. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18614. return false;
  18615. }
  18616. if (!this._cache.rotation.equals(this.rotation))
  18617. return false;
  18618. if (!this._cache.scaling.equals(this.scaling))
  18619. return false;
  18620. return true;
  18621. };
  18622. TransformNode.prototype._initCache = function () {
  18623. _super.prototype._initCache.call(this);
  18624. this._cache.localMatrixUpdated = false;
  18625. this._cache.position = BABYLON.Vector3.Zero();
  18626. this._cache.scaling = BABYLON.Vector3.Zero();
  18627. this._cache.rotation = BABYLON.Vector3.Zero();
  18628. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18629. this._cache.billboardMode = -1;
  18630. };
  18631. TransformNode.prototype.markAsDirty = function (property) {
  18632. if (property === "rotation") {
  18633. this.rotationQuaternion = null;
  18634. }
  18635. this._currentRenderId = Number.MAX_VALUE;
  18636. this._isDirty = true;
  18637. return this;
  18638. };
  18639. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18640. /**
  18641. * Returns the current mesh absolute position.
  18642. * Retuns a Vector3.
  18643. */
  18644. get: function () {
  18645. return this._absolutePosition;
  18646. },
  18647. enumerable: true,
  18648. configurable: true
  18649. });
  18650. /**
  18651. * Sets a new matrix to apply before all other transformation
  18652. * @param matrix defines the transform matrix
  18653. * @returns the current TransformNode
  18654. */
  18655. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18656. return this.setPivotMatrix(matrix, false);
  18657. };
  18658. /**
  18659. * Sets a new pivot matrix to the current node
  18660. * @param matrix defines the new pivot matrix to use
  18661. * @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
  18662. * @returns the current TransformNode
  18663. */
  18664. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18665. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18666. this._pivotMatrix = matrix.clone();
  18667. this._cache.pivotMatrixUpdated = true;
  18668. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18669. if (this._postMultiplyPivotMatrix) {
  18670. if (!this._pivotMatrixInverse) {
  18671. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18672. }
  18673. else {
  18674. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18675. }
  18676. }
  18677. return this;
  18678. };
  18679. /**
  18680. * Returns the mesh pivot matrix.
  18681. * Default : Identity.
  18682. * A Matrix is returned.
  18683. */
  18684. TransformNode.prototype.getPivotMatrix = function () {
  18685. return this._pivotMatrix;
  18686. };
  18687. /**
  18688. * Prevents the World matrix to be computed any longer.
  18689. * Returns the TransformNode.
  18690. */
  18691. TransformNode.prototype.freezeWorldMatrix = function () {
  18692. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18693. this.computeWorldMatrix(true);
  18694. this._isWorldMatrixFrozen = true;
  18695. return this;
  18696. };
  18697. /**
  18698. * Allows back the World matrix computation.
  18699. * Returns the TransformNode.
  18700. */
  18701. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18702. this._isWorldMatrixFrozen = false;
  18703. this.computeWorldMatrix(true);
  18704. return this;
  18705. };
  18706. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18707. /**
  18708. * True if the World matrix has been frozen.
  18709. * Returns a boolean.
  18710. */
  18711. get: function () {
  18712. return this._isWorldMatrixFrozen;
  18713. },
  18714. enumerable: true,
  18715. configurable: true
  18716. });
  18717. /**
  18718. * Retuns the mesh absolute position in the World.
  18719. * Returns a Vector3.
  18720. */
  18721. TransformNode.prototype.getAbsolutePosition = function () {
  18722. this.computeWorldMatrix();
  18723. return this._absolutePosition;
  18724. };
  18725. /**
  18726. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18727. * Returns the TransformNode.
  18728. */
  18729. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18730. if (!absolutePosition) {
  18731. return this;
  18732. }
  18733. var absolutePositionX;
  18734. var absolutePositionY;
  18735. var absolutePositionZ;
  18736. if (absolutePosition.x === undefined) {
  18737. if (arguments.length < 3) {
  18738. return this;
  18739. }
  18740. absolutePositionX = arguments[0];
  18741. absolutePositionY = arguments[1];
  18742. absolutePositionZ = arguments[2];
  18743. }
  18744. else {
  18745. absolutePositionX = absolutePosition.x;
  18746. absolutePositionY = absolutePosition.y;
  18747. absolutePositionZ = absolutePosition.z;
  18748. }
  18749. if (this.parent) {
  18750. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18751. invertParentWorldMatrix.invert();
  18752. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18753. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18754. }
  18755. else {
  18756. this.position.x = absolutePositionX;
  18757. this.position.y = absolutePositionY;
  18758. this.position.z = absolutePositionZ;
  18759. }
  18760. return this;
  18761. };
  18762. /**
  18763. * Sets the mesh position in its local space.
  18764. * Returns the TransformNode.
  18765. */
  18766. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18767. this.computeWorldMatrix();
  18768. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18769. return this;
  18770. };
  18771. /**
  18772. * Returns the mesh position in the local space from the current World matrix values.
  18773. * Returns a new Vector3.
  18774. */
  18775. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18776. this.computeWorldMatrix();
  18777. var invLocalWorldMatrix = this._localWorld.clone();
  18778. invLocalWorldMatrix.invert();
  18779. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18780. };
  18781. /**
  18782. * Translates the mesh along the passed Vector3 in its local space.
  18783. * Returns the TransformNode.
  18784. */
  18785. TransformNode.prototype.locallyTranslate = function (vector3) {
  18786. this.computeWorldMatrix(true);
  18787. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18788. return this;
  18789. };
  18790. /**
  18791. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18792. * @param targetPoint the position (must be in same space as current mesh) to look at
  18793. * @param yawCor optional yaw (y-axis) correction in radians
  18794. * @param pitchCor optional pitch (x-axis) correction in radians
  18795. * @param rollCor optional roll (z-axis) correction in radians
  18796. * @param space the choosen space of the target
  18797. * @returns the TransformNode.
  18798. */
  18799. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18800. if (yawCor === void 0) { yawCor = 0; }
  18801. if (pitchCor === void 0) { pitchCor = 0; }
  18802. if (rollCor === void 0) { rollCor = 0; }
  18803. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18804. var dv = TransformNode._lookAtVectorCache;
  18805. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18806. targetPoint.subtractToRef(pos, dv);
  18807. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18808. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18809. var pitch = Math.atan2(dv.y, len);
  18810. if (this.rotationQuaternion) {
  18811. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18812. }
  18813. else {
  18814. this.rotation.x = pitch + pitchCor;
  18815. this.rotation.y = yaw + yawCor;
  18816. this.rotation.z = rollCor;
  18817. }
  18818. return this;
  18819. };
  18820. /**
  18821. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18822. * This Vector3 is expressed in the World space.
  18823. */
  18824. TransformNode.prototype.getDirection = function (localAxis) {
  18825. var result = BABYLON.Vector3.Zero();
  18826. this.getDirectionToRef(localAxis, result);
  18827. return result;
  18828. };
  18829. /**
  18830. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18831. * localAxis is expressed in the mesh local space.
  18832. * result is computed in the Wordl space from the mesh World matrix.
  18833. * Returns the TransformNode.
  18834. */
  18835. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18836. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18837. return this;
  18838. };
  18839. /**
  18840. * Sets a new pivot point to the current node
  18841. * @param point defines the new pivot point to use
  18842. * @param space defines if the point is in world or local space (local by default)
  18843. * @returns the current TransformNode
  18844. */
  18845. TransformNode.prototype.setPivotPoint = function (point, space) {
  18846. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18847. if (this.getScene().getRenderId() == 0) {
  18848. this.computeWorldMatrix(true);
  18849. }
  18850. var wm = this.getWorldMatrix();
  18851. if (space == BABYLON.Space.WORLD) {
  18852. var tmat = BABYLON.Tmp.Matrix[0];
  18853. wm.invertToRef(tmat);
  18854. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18855. }
  18856. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18857. };
  18858. /**
  18859. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18860. */
  18861. TransformNode.prototype.getPivotPoint = function () {
  18862. var point = BABYLON.Vector3.Zero();
  18863. this.getPivotPointToRef(point);
  18864. return point;
  18865. };
  18866. /**
  18867. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18868. * Returns the TransformNode.
  18869. */
  18870. TransformNode.prototype.getPivotPointToRef = function (result) {
  18871. result.x = -this._pivotMatrix.m[12];
  18872. result.y = -this._pivotMatrix.m[13];
  18873. result.z = -this._pivotMatrix.m[14];
  18874. return this;
  18875. };
  18876. /**
  18877. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18878. */
  18879. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18880. var point = BABYLON.Vector3.Zero();
  18881. this.getAbsolutePivotPointToRef(point);
  18882. return point;
  18883. };
  18884. /**
  18885. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18886. * Returns the TransformNode.
  18887. */
  18888. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18889. result.x = this._pivotMatrix.m[12];
  18890. result.y = this._pivotMatrix.m[13];
  18891. result.z = this._pivotMatrix.m[14];
  18892. this.getPivotPointToRef(result);
  18893. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18894. return this;
  18895. };
  18896. /**
  18897. * Defines the passed node as the parent of the current node.
  18898. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18899. * Returns the TransformNode.
  18900. */
  18901. TransformNode.prototype.setParent = function (node) {
  18902. if (!node && !this.parent) {
  18903. return this;
  18904. }
  18905. if (!node) {
  18906. var rotation = BABYLON.Tmp.Quaternion[0];
  18907. var position = BABYLON.Tmp.Vector3[0];
  18908. var scale = BABYLON.Tmp.Vector3[1];
  18909. if (this.parent && this.parent.computeWorldMatrix) {
  18910. this.parent.computeWorldMatrix(true);
  18911. }
  18912. this.computeWorldMatrix(true);
  18913. this.getWorldMatrix().decompose(scale, rotation, position);
  18914. if (this.rotationQuaternion) {
  18915. this.rotationQuaternion.copyFrom(rotation);
  18916. }
  18917. else {
  18918. rotation.toEulerAnglesToRef(this.rotation);
  18919. }
  18920. this.scaling.x = scale.x;
  18921. this.scaling.y = scale.y;
  18922. this.scaling.z = scale.z;
  18923. this.position.x = position.x;
  18924. this.position.y = position.y;
  18925. this.position.z = position.z;
  18926. }
  18927. else {
  18928. var rotation = BABYLON.Tmp.Quaternion[0];
  18929. var position = BABYLON.Tmp.Vector3[0];
  18930. var scale = BABYLON.Tmp.Vector3[1];
  18931. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18932. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18933. this.computeWorldMatrix(true);
  18934. node.computeWorldMatrix(true);
  18935. node.getWorldMatrix().invertToRef(invParentMatrix);
  18936. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18937. diffMatrix.decompose(scale, rotation, position);
  18938. if (this.rotationQuaternion) {
  18939. this.rotationQuaternion.copyFrom(rotation);
  18940. }
  18941. else {
  18942. rotation.toEulerAnglesToRef(this.rotation);
  18943. }
  18944. this.position.x = position.x;
  18945. this.position.y = position.y;
  18946. this.position.z = position.z;
  18947. this.scaling.x = scale.x;
  18948. this.scaling.y = scale.y;
  18949. this.scaling.z = scale.z;
  18950. }
  18951. this.parent = node;
  18952. return this;
  18953. };
  18954. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18955. get: function () {
  18956. return this._nonUniformScaling;
  18957. },
  18958. enumerable: true,
  18959. configurable: true
  18960. });
  18961. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18962. if (this._nonUniformScaling === value) {
  18963. return false;
  18964. }
  18965. this._nonUniformScaling = value;
  18966. return true;
  18967. };
  18968. /**
  18969. * Attach the current TransformNode to another TransformNode associated with a bone
  18970. * @param bone Bone affecting the TransformNode
  18971. * @param affectedTransformNode TransformNode associated with the bone
  18972. */
  18973. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18974. this._transformToBoneReferal = affectedTransformNode;
  18975. this.parent = bone;
  18976. if (bone.getWorldMatrix().determinant() < 0) {
  18977. this.scalingDeterminant *= -1;
  18978. }
  18979. return this;
  18980. };
  18981. TransformNode.prototype.detachFromBone = function () {
  18982. if (!this.parent) {
  18983. return this;
  18984. }
  18985. if (this.parent.getWorldMatrix().determinant() < 0) {
  18986. this.scalingDeterminant *= -1;
  18987. }
  18988. this._transformToBoneReferal = null;
  18989. this.parent = null;
  18990. return this;
  18991. };
  18992. /**
  18993. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18994. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18995. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18996. * The passed axis is also normalized.
  18997. * Returns the TransformNode.
  18998. */
  18999. TransformNode.prototype.rotate = function (axis, amount, space) {
  19000. axis.normalize();
  19001. if (!this.rotationQuaternion) {
  19002. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19003. this.rotation = BABYLON.Vector3.Zero();
  19004. }
  19005. var rotationQuaternion;
  19006. if (!space || space === BABYLON.Space.LOCAL) {
  19007. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19008. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19009. }
  19010. else {
  19011. if (this.parent) {
  19012. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19013. invertParentWorldMatrix.invert();
  19014. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19015. }
  19016. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19017. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19018. }
  19019. return this;
  19020. };
  19021. /**
  19022. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19023. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19024. * The passed axis is also normalized.
  19025. * Returns the TransformNode.
  19026. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19027. */
  19028. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19029. axis.normalize();
  19030. if (!this.rotationQuaternion) {
  19031. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19032. this.rotation.copyFromFloats(0, 0, 0);
  19033. }
  19034. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19035. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19036. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19037. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19038. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19039. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19040. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19041. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19042. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19043. return this;
  19044. };
  19045. /**
  19046. * Translates the mesh along the axis vector for the passed distance in the given space.
  19047. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19048. * Returns the TransformNode.
  19049. */
  19050. TransformNode.prototype.translate = function (axis, distance, space) {
  19051. var displacementVector = axis.scale(distance);
  19052. if (!space || space === BABYLON.Space.LOCAL) {
  19053. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19054. this.setPositionWithLocalVector(tempV3);
  19055. }
  19056. else {
  19057. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19058. }
  19059. return this;
  19060. };
  19061. /**
  19062. * Adds a rotation step to the mesh current rotation.
  19063. * x, y, z are Euler angles expressed in radians.
  19064. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19065. * This means this rotation is made in the mesh local space only.
  19066. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19067. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19068. * ```javascript
  19069. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19070. * ```
  19071. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19072. * 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.
  19073. * Returns the TransformNode.
  19074. */
  19075. TransformNode.prototype.addRotation = function (x, y, z) {
  19076. var rotationQuaternion;
  19077. if (this.rotationQuaternion) {
  19078. rotationQuaternion = this.rotationQuaternion;
  19079. }
  19080. else {
  19081. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19082. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19083. }
  19084. var accumulation = BABYLON.Tmp.Quaternion[0];
  19085. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19086. rotationQuaternion.multiplyInPlace(accumulation);
  19087. if (!this.rotationQuaternion) {
  19088. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19089. }
  19090. return this;
  19091. };
  19092. /**
  19093. * Computes the mesh World matrix and returns it.
  19094. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19095. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19096. * If the parameter `force`is set to `true`, the actual computation is done.
  19097. * Returns the mesh World Matrix.
  19098. */
  19099. TransformNode.prototype.computeWorldMatrix = function (force) {
  19100. if (this._isWorldMatrixFrozen) {
  19101. return this._worldMatrix;
  19102. }
  19103. if (!force && this.isSynchronized(true)) {
  19104. this._currentRenderId = this.getScene().getRenderId();
  19105. return this._worldMatrix;
  19106. }
  19107. this._cache.position.copyFrom(this.position);
  19108. this._cache.scaling.copyFrom(this.scaling);
  19109. this._cache.pivotMatrixUpdated = false;
  19110. this._cache.billboardMode = this.billboardMode;
  19111. this._currentRenderId = this.getScene().getRenderId();
  19112. this._childRenderId = this.getScene().getRenderId();
  19113. this._isDirty = false;
  19114. // Scaling
  19115. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19116. // Rotation
  19117. //rotate, if quaternion is set and rotation was used
  19118. if (this.rotationQuaternion) {
  19119. var len = this.rotation.length();
  19120. if (len) {
  19121. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19122. this.rotation.copyFromFloats(0, 0, 0);
  19123. }
  19124. }
  19125. if (this.rotationQuaternion) {
  19126. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19127. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19128. }
  19129. else {
  19130. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19131. this._cache.rotation.copyFrom(this.rotation);
  19132. }
  19133. // Translation
  19134. var camera = this.getScene().activeCamera;
  19135. if (this.infiniteDistance && !this.parent && camera) {
  19136. var cameraWorldMatrix = camera.getWorldMatrix();
  19137. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19138. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19139. }
  19140. else {
  19141. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19142. }
  19143. // Composing transformations
  19144. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19145. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19146. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19147. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19148. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19149. // Need to decompose each rotation here
  19150. var currentPosition = BABYLON.Tmp.Vector3[3];
  19151. if (this.parent && this.parent.getWorldMatrix) {
  19152. if (this._transformToBoneReferal) {
  19153. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19154. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19155. }
  19156. else {
  19157. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19158. }
  19159. }
  19160. else {
  19161. currentPosition.copyFrom(this.position);
  19162. }
  19163. currentPosition.subtractInPlace(camera.globalPosition);
  19164. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19165. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19166. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19167. }
  19168. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19169. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19170. }
  19171. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19172. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19173. }
  19174. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19175. }
  19176. else {
  19177. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19178. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19179. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19180. }
  19181. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19182. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19183. }
  19184. // Local world
  19185. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19186. // Parent
  19187. if (this.parent && this.parent.getWorldMatrix) {
  19188. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19189. if (this._transformToBoneReferal) {
  19190. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19191. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19192. }
  19193. else {
  19194. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19195. }
  19196. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19197. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19198. this._worldMatrix.copyFrom(this._localWorld);
  19199. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19200. }
  19201. else {
  19202. if (this._transformToBoneReferal) {
  19203. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19204. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19205. }
  19206. else {
  19207. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19208. }
  19209. }
  19210. this._markSyncedWithParent();
  19211. }
  19212. else {
  19213. this._worldMatrix.copyFrom(this._localWorld);
  19214. }
  19215. // Post multiply inverse of pivotMatrix
  19216. if (this._postMultiplyPivotMatrix) {
  19217. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19218. }
  19219. // Normal matrix
  19220. if (!this.ignoreNonUniformScaling) {
  19221. if (this.scaling.isNonUniform) {
  19222. this._updateNonUniformScalingState(true);
  19223. }
  19224. else if (this.parent && this.parent._nonUniformScaling) {
  19225. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19226. }
  19227. else {
  19228. this._updateNonUniformScalingState(false);
  19229. }
  19230. }
  19231. else {
  19232. this._updateNonUniformScalingState(false);
  19233. }
  19234. this._afterComputeWorldMatrix();
  19235. // Absolute position
  19236. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19237. // Callbacks
  19238. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19239. if (!this._poseMatrix) {
  19240. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19241. }
  19242. // Cache the determinant
  19243. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19244. return this._worldMatrix;
  19245. };
  19246. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19247. };
  19248. /**
  19249. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19250. * @param func: callback function to add
  19251. *
  19252. * Returns the TransformNode.
  19253. */
  19254. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19255. this.onAfterWorldMatrixUpdateObservable.add(func);
  19256. return this;
  19257. };
  19258. /**
  19259. * Removes a registered callback function.
  19260. * Returns the TransformNode.
  19261. */
  19262. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19263. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19264. return this;
  19265. };
  19266. /**
  19267. * Clone the current transform node
  19268. * Returns the new transform node
  19269. * @param name Name of the new clone
  19270. * @param newParent New parent for the clone
  19271. * @param doNotCloneChildren Do not clone children hierarchy
  19272. */
  19273. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19274. var _this = this;
  19275. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19276. result.name = name;
  19277. result.id = name;
  19278. if (newParent) {
  19279. result.parent = newParent;
  19280. }
  19281. if (!doNotCloneChildren) {
  19282. // Children
  19283. var directDescendants = this.getDescendants(true);
  19284. for (var index = 0; index < directDescendants.length; index++) {
  19285. var child = directDescendants[index];
  19286. if (child.clone) {
  19287. child.clone(name + "." + child.name, result);
  19288. }
  19289. }
  19290. }
  19291. return result;
  19292. };
  19293. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19294. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19295. serializationObject.type = this.getClassName();
  19296. // Parent
  19297. if (this.parent) {
  19298. serializationObject.parentId = this.parent.id;
  19299. }
  19300. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19301. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19302. }
  19303. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19304. serializationObject.isEnabled = this.isEnabled();
  19305. // Parent
  19306. if (this.parent) {
  19307. serializationObject.parentId = this.parent.id;
  19308. }
  19309. return serializationObject;
  19310. };
  19311. // Statics
  19312. /**
  19313. * Returns a new TransformNode object parsed from the source provided.
  19314. * The parameter `parsedMesh` is the source.
  19315. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19316. */
  19317. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19318. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19319. if (BABYLON.Tags) {
  19320. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19321. }
  19322. if (parsedTransformNode.localMatrix) {
  19323. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19324. }
  19325. else if (parsedTransformNode.pivotMatrix) {
  19326. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19327. }
  19328. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19329. // Parent
  19330. if (parsedTransformNode.parentId) {
  19331. transformNode._waitingParentId = parsedTransformNode.parentId;
  19332. }
  19333. return transformNode;
  19334. };
  19335. /**
  19336. * Releases resources associated with this transform node.
  19337. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19338. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19339. */
  19340. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19341. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19342. // Animations
  19343. this.getScene().stopAnimation(this);
  19344. // Remove from scene
  19345. this.getScene().removeTransformNode(this);
  19346. this.onAfterWorldMatrixUpdateObservable.clear();
  19347. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19348. };
  19349. // Statics
  19350. TransformNode.BILLBOARDMODE_NONE = 0;
  19351. TransformNode.BILLBOARDMODE_X = 1;
  19352. TransformNode.BILLBOARDMODE_Y = 2;
  19353. TransformNode.BILLBOARDMODE_Z = 4;
  19354. TransformNode.BILLBOARDMODE_ALL = 7;
  19355. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19356. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19357. __decorate([
  19358. BABYLON.serializeAsVector3()
  19359. ], TransformNode.prototype, "_rotation", void 0);
  19360. __decorate([
  19361. BABYLON.serializeAsQuaternion()
  19362. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19363. __decorate([
  19364. BABYLON.serializeAsVector3()
  19365. ], TransformNode.prototype, "_scaling", void 0);
  19366. __decorate([
  19367. BABYLON.serialize()
  19368. ], TransformNode.prototype, "billboardMode", void 0);
  19369. __decorate([
  19370. BABYLON.serialize()
  19371. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19372. __decorate([
  19373. BABYLON.serialize()
  19374. ], TransformNode.prototype, "infiniteDistance", void 0);
  19375. __decorate([
  19376. BABYLON.serialize()
  19377. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19378. __decorate([
  19379. BABYLON.serializeAsVector3()
  19380. ], TransformNode.prototype, "position", void 0);
  19381. return TransformNode;
  19382. }(BABYLON.Node));
  19383. BABYLON.TransformNode = TransformNode;
  19384. })(BABYLON || (BABYLON = {}));
  19385. //# sourceMappingURL=babylon.transformNode.js.map
  19386. var BABYLON;
  19387. (function (BABYLON) {
  19388. /**
  19389. * Class used to store all common mesh properties
  19390. */
  19391. var AbstractMesh = /** @class */ (function (_super) {
  19392. __extends(AbstractMesh, _super);
  19393. // Constructor
  19394. /**
  19395. * Creates a new AbstractMesh
  19396. * @param name defines the name of the mesh
  19397. * @param scene defines the hosting scene
  19398. */
  19399. function AbstractMesh(name, scene) {
  19400. if (scene === void 0) { scene = null; }
  19401. var _this = _super.call(this, name, scene, false) || this;
  19402. _this._facetNb = 0; // facet number
  19403. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19404. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19405. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19406. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19407. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19408. _this._subDiv = {
  19409. max: 1,
  19410. X: 1,
  19411. Y: 1,
  19412. Z: 1
  19413. };
  19414. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19415. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19416. // Events
  19417. /**
  19418. * An event triggered when this mesh collides with another one
  19419. */
  19420. _this.onCollideObservable = new BABYLON.Observable();
  19421. /**
  19422. * An event triggered when the collision's position changes
  19423. */
  19424. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19425. /**
  19426. * An event triggered when material is changed
  19427. */
  19428. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19429. // Properties
  19430. /**
  19431. * Gets or sets the orientation for POV movement & rotation
  19432. */
  19433. _this.definedFacingForward = true;
  19434. /**
  19435. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19436. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19437. * * 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.
  19438. * @see http://doc.babylonjs.com/features/occlusionquery
  19439. */
  19440. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19441. /**
  19442. * 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:
  19443. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19444. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19445. * * 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.
  19446. * @see http://doc.babylonjs.com/features/occlusionquery
  19447. */
  19448. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19449. /**
  19450. * 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.
  19451. * The default value is -1 which means don't break the query and wait till the result
  19452. * @see http://doc.babylonjs.com/features/occlusionquery
  19453. */
  19454. _this.occlusionRetryCount = -1;
  19455. _this._occlusionInternalRetryCounter = 0;
  19456. _this._isOccluded = false;
  19457. _this._isOcclusionQueryInProgress = false;
  19458. _this._visibility = 1.0;
  19459. /** Gets or sets the alpha index used to sort transparent meshes
  19460. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19461. */
  19462. _this.alphaIndex = Number.MAX_VALUE;
  19463. /**
  19464. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19465. */
  19466. _this.isVisible = true;
  19467. /**
  19468. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19469. */
  19470. _this.isPickable = true;
  19471. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19472. _this.showSubMeshesBoundingBox = false;
  19473. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19474. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19475. */
  19476. _this.isBlocker = false;
  19477. /**
  19478. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19479. */
  19480. _this.enablePointerMoveEvents = false;
  19481. /**
  19482. * Specifies the rendering group id for this mesh (0 by default)
  19483. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19484. */
  19485. _this.renderingGroupId = 0;
  19486. _this._receiveShadows = false;
  19487. /**
  19488. * Gets or sets a boolean indicating if the outline must be rendered as well
  19489. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19490. */
  19491. _this.renderOutline = false;
  19492. /** Defines color to use when rendering outline */
  19493. _this.outlineColor = BABYLON.Color3.Red();
  19494. /** Define width to use when rendering outline */
  19495. _this.outlineWidth = 0.02;
  19496. /**
  19497. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19498. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19499. */
  19500. _this.renderOverlay = false;
  19501. /** Defines color to use when rendering overlay */
  19502. _this.overlayColor = BABYLON.Color3.Red();
  19503. /** Defines alpha to use when rendering overlay */
  19504. _this.overlayAlpha = 0.5;
  19505. _this._hasVertexAlpha = false;
  19506. _this._useVertexColors = true;
  19507. _this._computeBonesUsingShaders = true;
  19508. _this._numBoneInfluencers = 4;
  19509. _this._applyFog = true;
  19510. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19511. _this.useOctreeForRenderingSelection = true;
  19512. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19513. _this.useOctreeForPicking = true;
  19514. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19515. _this.useOctreeForCollisions = true;
  19516. _this._layerMask = 0x0FFFFFFF;
  19517. /**
  19518. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19519. */
  19520. _this.alwaysSelectAsActiveMesh = false;
  19521. /**
  19522. * Gets or sets the current action manager
  19523. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19524. */
  19525. _this.actionManager = null;
  19526. /**
  19527. * Gets or sets impostor used for physic simulation
  19528. * @see http://doc.babylonjs.com/features/physics_engine
  19529. */
  19530. _this.physicsImpostor = null;
  19531. // Collisions
  19532. _this._checkCollisions = false;
  19533. _this._collisionMask = -1;
  19534. _this._collisionGroup = -1;
  19535. /**
  19536. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19537. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19538. */
  19539. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19540. /**
  19541. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19542. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19543. */
  19544. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19545. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19546. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19547. // Edges
  19548. /**
  19549. * Defines edge width used when edgesRenderer is enabled
  19550. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19551. */
  19552. _this.edgesWidth = 1;
  19553. /**
  19554. * Defines edge color used when edgesRenderer is enabled
  19555. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19556. */
  19557. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19558. // Cache
  19559. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19560. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19561. /** @hidden */
  19562. _this._renderId = 0;
  19563. /** @hidden */
  19564. _this._intersectionsInProgress = new Array();
  19565. /** @hidden */
  19566. _this._unIndexed = false;
  19567. /** @hidden */
  19568. _this._lightSources = new Array();
  19569. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19570. if (collidedMesh === void 0) { collidedMesh = null; }
  19571. //TODO move this to the collision coordinator!
  19572. if (_this.getScene().workerCollisions)
  19573. newPosition.multiplyInPlace(_this._collider._radius);
  19574. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19575. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19576. _this.position.addInPlace(_this._diffPositionForCollisions);
  19577. }
  19578. if (collidedMesh) {
  19579. _this.onCollideObservable.notifyObservers(collidedMesh);
  19580. }
  19581. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19582. };
  19583. _this.getScene().addMesh(_this);
  19584. _this._resyncLightSources();
  19585. return _this;
  19586. }
  19587. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19588. /**
  19589. * No billboard
  19590. */
  19591. get: function () {
  19592. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19593. },
  19594. enumerable: true,
  19595. configurable: true
  19596. });
  19597. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19598. /** Billboard on X axis */
  19599. get: function () {
  19600. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19601. },
  19602. enumerable: true,
  19603. configurable: true
  19604. });
  19605. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19606. /** Billboard on Y axis */
  19607. get: function () {
  19608. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19609. },
  19610. enumerable: true,
  19611. configurable: true
  19612. });
  19613. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19614. /** Billboard on Z axis */
  19615. get: function () {
  19616. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19617. },
  19618. enumerable: true,
  19619. configurable: true
  19620. });
  19621. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19622. /** Billboard on all axes */
  19623. get: function () {
  19624. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19625. },
  19626. enumerable: true,
  19627. configurable: true
  19628. });
  19629. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19630. /**
  19631. * Gets the number of facets in the mesh
  19632. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19633. */
  19634. get: function () {
  19635. return this._facetNb;
  19636. },
  19637. enumerable: true,
  19638. configurable: true
  19639. });
  19640. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19641. /**
  19642. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19643. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19644. */
  19645. get: function () {
  19646. return this._partitioningSubdivisions;
  19647. },
  19648. set: function (nb) {
  19649. this._partitioningSubdivisions = nb;
  19650. },
  19651. enumerable: true,
  19652. configurable: true
  19653. });
  19654. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19655. /**
  19656. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19657. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19658. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19659. */
  19660. get: function () {
  19661. return this._partitioningBBoxRatio;
  19662. },
  19663. set: function (ratio) {
  19664. this._partitioningBBoxRatio = ratio;
  19665. },
  19666. enumerable: true,
  19667. configurable: true
  19668. });
  19669. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19670. /**
  19671. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19672. * Works only for updatable meshes.
  19673. * Doesn't work with multi-materials
  19674. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19675. */
  19676. get: function () {
  19677. return this._facetDepthSort;
  19678. },
  19679. set: function (sort) {
  19680. this._facetDepthSort = sort;
  19681. },
  19682. enumerable: true,
  19683. configurable: true
  19684. });
  19685. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19686. /**
  19687. * The location (Vector3) where the facet depth sort must be computed from.
  19688. * By default, the active camera position.
  19689. * Used only when facet depth sort is enabled
  19690. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19691. */
  19692. get: function () {
  19693. return this._facetDepthSortFrom;
  19694. },
  19695. set: function (location) {
  19696. this._facetDepthSortFrom = location;
  19697. },
  19698. enumerable: true,
  19699. configurable: true
  19700. });
  19701. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19702. /**
  19703. * gets a boolean indicating if facetData is enabled
  19704. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19705. */
  19706. get: function () {
  19707. return this._facetDataEnabled;
  19708. },
  19709. enumerable: true,
  19710. configurable: true
  19711. });
  19712. /** @hidden */
  19713. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19714. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19715. return false;
  19716. }
  19717. this._markSubMeshesAsMiscDirty();
  19718. return true;
  19719. };
  19720. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19721. /** Set a function to call when this mesh collides with another one */
  19722. set: function (callback) {
  19723. if (this._onCollideObserver) {
  19724. this.onCollideObservable.remove(this._onCollideObserver);
  19725. }
  19726. this._onCollideObserver = this.onCollideObservable.add(callback);
  19727. },
  19728. enumerable: true,
  19729. configurable: true
  19730. });
  19731. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19732. /** Set a function to call when the collision's position changes */
  19733. set: function (callback) {
  19734. if (this._onCollisionPositionChangeObserver) {
  19735. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19736. }
  19737. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19738. },
  19739. enumerable: true,
  19740. configurable: true
  19741. });
  19742. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19743. /**
  19744. * 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
  19745. * @see http://doc.babylonjs.com/features/occlusionquery
  19746. */
  19747. get: function () {
  19748. return this._isOccluded;
  19749. },
  19750. set: function (value) {
  19751. this._isOccluded = value;
  19752. },
  19753. enumerable: true,
  19754. configurable: true
  19755. });
  19756. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19757. /**
  19758. * Flag to check the progress status of the query
  19759. * @see http://doc.babylonjs.com/features/occlusionquery
  19760. */
  19761. get: function () {
  19762. return this._isOcclusionQueryInProgress;
  19763. },
  19764. enumerable: true,
  19765. configurable: true
  19766. });
  19767. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19768. /**
  19769. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19770. */
  19771. get: function () {
  19772. return this._visibility;
  19773. },
  19774. /**
  19775. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19776. */
  19777. set: function (value) {
  19778. if (this._visibility === value) {
  19779. return;
  19780. }
  19781. this._visibility = value;
  19782. this._markSubMeshesAsMiscDirty();
  19783. },
  19784. enumerable: true,
  19785. configurable: true
  19786. });
  19787. Object.defineProperty(AbstractMesh.prototype, "material", {
  19788. /** Gets or sets current material */
  19789. get: function () {
  19790. return this._material;
  19791. },
  19792. set: function (value) {
  19793. if (this._material === value) {
  19794. return;
  19795. }
  19796. this._material = value;
  19797. if (this.onMaterialChangedObservable.hasObservers) {
  19798. this.onMaterialChangedObservable.notifyObservers(this);
  19799. }
  19800. if (!this.subMeshes) {
  19801. return;
  19802. }
  19803. this._unBindEffect();
  19804. },
  19805. enumerable: true,
  19806. configurable: true
  19807. });
  19808. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19809. /**
  19810. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19811. * @see http://doc.babylonjs.com/babylon101/shadows
  19812. */
  19813. get: function () {
  19814. return this._receiveShadows;
  19815. },
  19816. set: function (value) {
  19817. if (this._receiveShadows === value) {
  19818. return;
  19819. }
  19820. this._receiveShadows = value;
  19821. this._markSubMeshesAsLightDirty();
  19822. },
  19823. enumerable: true,
  19824. configurable: true
  19825. });
  19826. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19827. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19828. get: function () {
  19829. return this._hasVertexAlpha;
  19830. },
  19831. set: function (value) {
  19832. if (this._hasVertexAlpha === value) {
  19833. return;
  19834. }
  19835. this._hasVertexAlpha = value;
  19836. this._markSubMeshesAsAttributesDirty();
  19837. this._markSubMeshesAsMiscDirty();
  19838. },
  19839. enumerable: true,
  19840. configurable: true
  19841. });
  19842. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19843. /** 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) */
  19844. get: function () {
  19845. return this._useVertexColors;
  19846. },
  19847. set: function (value) {
  19848. if (this._useVertexColors === value) {
  19849. return;
  19850. }
  19851. this._useVertexColors = value;
  19852. this._markSubMeshesAsAttributesDirty();
  19853. },
  19854. enumerable: true,
  19855. configurable: true
  19856. });
  19857. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19858. /**
  19859. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19860. */
  19861. get: function () {
  19862. return this._computeBonesUsingShaders;
  19863. },
  19864. set: function (value) {
  19865. if (this._computeBonesUsingShaders === value) {
  19866. return;
  19867. }
  19868. this._computeBonesUsingShaders = value;
  19869. this._markSubMeshesAsAttributesDirty();
  19870. },
  19871. enumerable: true,
  19872. configurable: true
  19873. });
  19874. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19875. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19876. get: function () {
  19877. return this._numBoneInfluencers;
  19878. },
  19879. set: function (value) {
  19880. if (this._numBoneInfluencers === value) {
  19881. return;
  19882. }
  19883. this._numBoneInfluencers = value;
  19884. this._markSubMeshesAsAttributesDirty();
  19885. },
  19886. enumerable: true,
  19887. configurable: true
  19888. });
  19889. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19890. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19891. get: function () {
  19892. return this._applyFog;
  19893. },
  19894. set: function (value) {
  19895. if (this._applyFog === value) {
  19896. return;
  19897. }
  19898. this._applyFog = value;
  19899. this._markSubMeshesAsMiscDirty();
  19900. },
  19901. enumerable: true,
  19902. configurable: true
  19903. });
  19904. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19905. /**
  19906. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19907. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19908. */
  19909. get: function () {
  19910. return this._layerMask;
  19911. },
  19912. set: function (value) {
  19913. if (value === this._layerMask) {
  19914. return;
  19915. }
  19916. this._layerMask = value;
  19917. this._resyncLightSources();
  19918. },
  19919. enumerable: true,
  19920. configurable: true
  19921. });
  19922. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19923. /**
  19924. * Gets or sets a collision mask used to mask collisions (default is -1).
  19925. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19926. */
  19927. get: function () {
  19928. return this._collisionMask;
  19929. },
  19930. set: function (mask) {
  19931. this._collisionMask = !isNaN(mask) ? mask : -1;
  19932. },
  19933. enumerable: true,
  19934. configurable: true
  19935. });
  19936. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19937. /**
  19938. * Gets or sets the current collision group mask (-1 by default).
  19939. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19940. */
  19941. get: function () {
  19942. return this._collisionGroup;
  19943. },
  19944. set: function (mask) {
  19945. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19946. },
  19947. enumerable: true,
  19948. configurable: true
  19949. });
  19950. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19951. /** @hidden */
  19952. get: function () {
  19953. return null;
  19954. },
  19955. enumerable: true,
  19956. configurable: true
  19957. });
  19958. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19959. get: function () {
  19960. return this._skeleton;
  19961. },
  19962. /**
  19963. * Gets or sets a skeleton to apply skining transformations
  19964. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19965. */
  19966. set: function (value) {
  19967. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19968. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19969. }
  19970. if (value && value.needInitialSkinMatrix) {
  19971. value._registerMeshWithPoseMatrix(this);
  19972. }
  19973. this._skeleton = value;
  19974. if (!this._skeleton) {
  19975. this._bonesTransformMatrices = null;
  19976. }
  19977. this._markSubMeshesAsAttributesDirty();
  19978. },
  19979. enumerable: true,
  19980. configurable: true
  19981. });
  19982. /**
  19983. * Returns the string "AbstractMesh"
  19984. * @returns "AbstractMesh"
  19985. */
  19986. AbstractMesh.prototype.getClassName = function () {
  19987. return "AbstractMesh";
  19988. };
  19989. /**
  19990. * Gets a string representation of the current mesh
  19991. * @param fullDetails defines a boolean indicating if full details must be included
  19992. * @returns a string representation of the current mesh
  19993. */
  19994. AbstractMesh.prototype.toString = function (fullDetails) {
  19995. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19996. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19997. if (this._skeleton) {
  19998. ret += ", skeleton: " + this._skeleton.name;
  19999. }
  20000. if (fullDetails) {
  20001. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20002. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20003. }
  20004. return ret;
  20005. };
  20006. /** @hidden */
  20007. AbstractMesh.prototype._rebuild = function () {
  20008. if (this._occlusionQuery) {
  20009. this._occlusionQuery = null;
  20010. }
  20011. if (this._edgesRenderer) {
  20012. this._edgesRenderer._rebuild();
  20013. }
  20014. if (!this.subMeshes) {
  20015. return;
  20016. }
  20017. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20018. var subMesh = _a[_i];
  20019. subMesh._rebuild();
  20020. }
  20021. };
  20022. /** @hidden */
  20023. AbstractMesh.prototype._resyncLightSources = function () {
  20024. this._lightSources.length = 0;
  20025. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20026. var light = _a[_i];
  20027. if (!light.isEnabled()) {
  20028. continue;
  20029. }
  20030. if (light.canAffectMesh(this)) {
  20031. this._lightSources.push(light);
  20032. }
  20033. }
  20034. this._markSubMeshesAsLightDirty();
  20035. };
  20036. /** @hidden */
  20037. AbstractMesh.prototype._resyncLighSource = function (light) {
  20038. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20039. var index = this._lightSources.indexOf(light);
  20040. if (index === -1) {
  20041. if (!isIn) {
  20042. return;
  20043. }
  20044. this._lightSources.push(light);
  20045. }
  20046. else {
  20047. if (isIn) {
  20048. return;
  20049. }
  20050. this._lightSources.splice(index, 1);
  20051. }
  20052. this._markSubMeshesAsLightDirty();
  20053. };
  20054. /** @hidden */
  20055. AbstractMesh.prototype._unBindEffect = function () {
  20056. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20057. var subMesh = _a[_i];
  20058. subMesh.setEffect(null);
  20059. }
  20060. };
  20061. /** @hidden */
  20062. AbstractMesh.prototype._removeLightSource = function (light) {
  20063. var index = this._lightSources.indexOf(light);
  20064. if (index === -1) {
  20065. return;
  20066. }
  20067. this._lightSources.splice(index, 1);
  20068. this._markSubMeshesAsLightDirty();
  20069. };
  20070. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20071. if (!this.subMeshes) {
  20072. return;
  20073. }
  20074. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20075. var subMesh = _a[_i];
  20076. if (subMesh._materialDefines) {
  20077. func(subMesh._materialDefines);
  20078. }
  20079. }
  20080. };
  20081. /** @hidden */
  20082. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20083. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20084. };
  20085. /** @hidden */
  20086. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20087. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20088. };
  20089. /** @hidden */
  20090. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20091. if (!this.subMeshes) {
  20092. return;
  20093. }
  20094. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20095. var subMesh = _a[_i];
  20096. var material = subMesh.getMaterial();
  20097. if (material) {
  20098. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20099. }
  20100. }
  20101. };
  20102. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20103. /**
  20104. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20105. */
  20106. get: function () {
  20107. return this._scaling;
  20108. },
  20109. set: function (newScaling) {
  20110. this._scaling = newScaling;
  20111. if (this.physicsImpostor) {
  20112. this.physicsImpostor.forceUpdate();
  20113. }
  20114. },
  20115. enumerable: true,
  20116. configurable: true
  20117. });
  20118. // Methods
  20119. /**
  20120. * Disables the mesh edge rendering mode
  20121. * @returns the currentAbstractMesh
  20122. */
  20123. AbstractMesh.prototype.disableEdgesRendering = function () {
  20124. if (this._edgesRenderer) {
  20125. this._edgesRenderer.dispose();
  20126. this._edgesRenderer = null;
  20127. }
  20128. return this;
  20129. };
  20130. /**
  20131. * Enables the edge rendering mode on the mesh.
  20132. * This mode makes the mesh edges visible
  20133. * @param epsilon defines the maximal distance between two angles to detect a face
  20134. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20135. * @returns the currentAbstractMesh
  20136. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20137. */
  20138. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20139. if (epsilon === void 0) { epsilon = 0.95; }
  20140. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20141. this.disableEdgesRendering();
  20142. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20143. return this;
  20144. };
  20145. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20146. /**
  20147. * Gets the edgesRenderer associated with the mesh
  20148. */
  20149. get: function () {
  20150. return this._edgesRenderer;
  20151. },
  20152. enumerable: true,
  20153. configurable: true
  20154. });
  20155. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20156. /**
  20157. * Returns true if the mesh is blocked. Implemented by child classes
  20158. */
  20159. get: function () {
  20160. return false;
  20161. },
  20162. enumerable: true,
  20163. configurable: true
  20164. });
  20165. /**
  20166. * Returns the mesh itself by default. Implemented by child classes
  20167. * @param camera defines the camera to use to pick the right LOD level
  20168. * @returns the currentAbstractMesh
  20169. */
  20170. AbstractMesh.prototype.getLOD = function (camera) {
  20171. return this;
  20172. };
  20173. /**
  20174. * Returns 0 by default. Implemented by child classes
  20175. * @returns an integer
  20176. */
  20177. AbstractMesh.prototype.getTotalVertices = function () {
  20178. return 0;
  20179. };
  20180. /**
  20181. * Returns null by default. Implemented by child classes
  20182. * @returns null
  20183. */
  20184. AbstractMesh.prototype.getIndices = function () {
  20185. return null;
  20186. };
  20187. /**
  20188. * Returns the array of the requested vertex data kind. Implemented by child classes
  20189. * @param kind defines the vertex data kind to use
  20190. * @returns null
  20191. */
  20192. AbstractMesh.prototype.getVerticesData = function (kind) {
  20193. return null;
  20194. };
  20195. /**
  20196. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20197. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20198. * Note that a new underlying VertexBuffer object is created each call.
  20199. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20200. * @param kind defines vertex data kind:
  20201. * * BABYLON.VertexBuffer.PositionKind
  20202. * * BABYLON.VertexBuffer.UVKind
  20203. * * BABYLON.VertexBuffer.UV2Kind
  20204. * * BABYLON.VertexBuffer.UV3Kind
  20205. * * BABYLON.VertexBuffer.UV4Kind
  20206. * * BABYLON.VertexBuffer.UV5Kind
  20207. * * BABYLON.VertexBuffer.UV6Kind
  20208. * * BABYLON.VertexBuffer.ColorKind
  20209. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20210. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20211. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20212. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20213. * @param data defines the data source
  20214. * @param updatable defines if the data must be flagged as updatable (or static)
  20215. * @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
  20216. * @returns the current mesh
  20217. */
  20218. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20219. return this;
  20220. };
  20221. /**
  20222. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20223. * If the mesh has no geometry, it is simply returned as it is.
  20224. * @param kind defines vertex data kind:
  20225. * * BABYLON.VertexBuffer.PositionKind
  20226. * * BABYLON.VertexBuffer.UVKind
  20227. * * BABYLON.VertexBuffer.UV2Kind
  20228. * * BABYLON.VertexBuffer.UV3Kind
  20229. * * BABYLON.VertexBuffer.UV4Kind
  20230. * * BABYLON.VertexBuffer.UV5Kind
  20231. * * BABYLON.VertexBuffer.UV6Kind
  20232. * * BABYLON.VertexBuffer.ColorKind
  20233. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20234. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20235. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20236. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20237. * @param data defines the data source
  20238. * @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
  20239. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20240. * @returns the current mesh
  20241. */
  20242. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20243. return this;
  20244. };
  20245. /**
  20246. * Sets the mesh indices,
  20247. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20248. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20249. * @param totalVertices Defines the total number of vertices
  20250. * @returns the current mesh
  20251. */
  20252. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20253. return this;
  20254. };
  20255. /**
  20256. * Gets a boolean indicating if specific vertex data is present
  20257. * @param kind defines the vertex data kind to use
  20258. * @returns true is data kind is present
  20259. */
  20260. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20261. return false;
  20262. };
  20263. /**
  20264. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20265. * @returns a BoundingInfo
  20266. */
  20267. AbstractMesh.prototype.getBoundingInfo = function () {
  20268. if (this._masterMesh) {
  20269. return this._masterMesh.getBoundingInfo();
  20270. }
  20271. if (!this._boundingInfo) {
  20272. // this._boundingInfo is being created here
  20273. this._updateBoundingInfo();
  20274. }
  20275. // cannot be null.
  20276. return this._boundingInfo;
  20277. };
  20278. /**
  20279. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20280. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20281. * @returns the current mesh
  20282. */
  20283. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20284. if (includeDescendants === void 0) { includeDescendants = true; }
  20285. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20286. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20287. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20288. if (maxDimension === 0) {
  20289. return this;
  20290. }
  20291. var scale = 1 / maxDimension;
  20292. this.scaling.scaleInPlace(scale);
  20293. return this;
  20294. };
  20295. /**
  20296. * Overwrite the current bounding info
  20297. * @param boundingInfo defines the new bounding info
  20298. * @returns the current mesh
  20299. */
  20300. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20301. this._boundingInfo = boundingInfo;
  20302. return this;
  20303. };
  20304. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20305. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20306. get: function () {
  20307. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20308. },
  20309. enumerable: true,
  20310. configurable: true
  20311. });
  20312. /** @hidden */
  20313. AbstractMesh.prototype._preActivate = function () {
  20314. };
  20315. /** @hidden */
  20316. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20317. };
  20318. /** @hidden */
  20319. AbstractMesh.prototype._activate = function (renderId) {
  20320. this._renderId = renderId;
  20321. };
  20322. /**
  20323. * Gets the current world matrix
  20324. * @returns a Matrix
  20325. */
  20326. AbstractMesh.prototype.getWorldMatrix = function () {
  20327. if (this._masterMesh) {
  20328. return this._masterMesh.getWorldMatrix();
  20329. }
  20330. return _super.prototype.getWorldMatrix.call(this);
  20331. };
  20332. /** @hidden */
  20333. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20334. if (this._masterMesh) {
  20335. return this._masterMesh._getWorldMatrixDeterminant();
  20336. }
  20337. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20338. };
  20339. // ================================== Point of View Movement =================================
  20340. /**
  20341. * Perform relative position change from the point of view of behind the front of the mesh.
  20342. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20343. * Supports definition of mesh facing forward or backward
  20344. * @param amountRight defines the distance on the right axis
  20345. * @param amountUp defines the distance on the up axis
  20346. * @param amountForward defines the distance on the forward axis
  20347. * @returns the current mesh
  20348. */
  20349. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20350. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20351. return this;
  20352. };
  20353. /**
  20354. * Calculate relative position change from the point of view of behind the front of the mesh.
  20355. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20356. * Supports definition of mesh facing forward or backward
  20357. * @param amountRight defines the distance on the right axis
  20358. * @param amountUp defines the distance on the up axis
  20359. * @param amountForward defines the distance on the forward axis
  20360. * @returns the new displacement vector
  20361. */
  20362. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20363. var rotMatrix = new BABYLON.Matrix();
  20364. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20365. rotQuaternion.toRotationMatrix(rotMatrix);
  20366. var translationDelta = BABYLON.Vector3.Zero();
  20367. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20368. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20369. return translationDelta;
  20370. };
  20371. // ================================== Point of View Rotation =================================
  20372. /**
  20373. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20374. * Supports definition of mesh facing forward or backward
  20375. * @param flipBack defines the flip
  20376. * @param twirlClockwise defines the twirl
  20377. * @param tiltRight defines the tilt
  20378. * @returns the current mesh
  20379. */
  20380. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20381. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20382. return this;
  20383. };
  20384. /**
  20385. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20386. * Supports definition of mesh facing forward or backward.
  20387. * @param flipBack defines the flip
  20388. * @param twirlClockwise defines the twirl
  20389. * @param tiltRight defines the tilt
  20390. * @returns the new rotation vector
  20391. */
  20392. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20393. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20394. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20395. };
  20396. /**
  20397. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20398. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20399. * @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
  20400. * @returns the new bounding vectors
  20401. */
  20402. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20403. if (includeDescendants === void 0) { includeDescendants = true; }
  20404. if (predicate === void 0) { predicate = null; }
  20405. // Ensures that all world matrix will be recomputed.
  20406. this.getScene().incrementRenderId();
  20407. this.computeWorldMatrix(true);
  20408. var min;
  20409. var max;
  20410. var boundingInfo = this.getBoundingInfo();
  20411. if (!this.subMeshes) {
  20412. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20413. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20414. }
  20415. else {
  20416. min = boundingInfo.boundingBox.minimumWorld;
  20417. max = boundingInfo.boundingBox.maximumWorld;
  20418. }
  20419. if (includeDescendants) {
  20420. var descendants = this.getDescendants(false);
  20421. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20422. var descendant = descendants_1[_i];
  20423. var childMesh = descendant;
  20424. childMesh.computeWorldMatrix(true);
  20425. // Filters meshes based on custom predicate function.
  20426. if (predicate && !predicate(childMesh)) {
  20427. continue;
  20428. }
  20429. //make sure we have the needed params to get mix and max
  20430. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20431. continue;
  20432. }
  20433. var childBoundingInfo = childMesh.getBoundingInfo();
  20434. var boundingBox = childBoundingInfo.boundingBox;
  20435. var minBox = boundingBox.minimumWorld;
  20436. var maxBox = boundingBox.maximumWorld;
  20437. BABYLON.Tools.CheckExtends(minBox, min, max);
  20438. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20439. }
  20440. }
  20441. return {
  20442. min: min,
  20443. max: max
  20444. };
  20445. };
  20446. /** @hidden */
  20447. AbstractMesh.prototype._updateBoundingInfo = function () {
  20448. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20449. this._boundingInfo.update(this.worldMatrixFromCache);
  20450. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20451. return this;
  20452. };
  20453. /** @hidden */
  20454. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20455. if (!this.subMeshes) {
  20456. return this;
  20457. }
  20458. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20459. var subMesh = this.subMeshes[subIndex];
  20460. if (!subMesh.IsGlobal) {
  20461. subMesh.updateBoundingInfo(matrix);
  20462. }
  20463. }
  20464. return this;
  20465. };
  20466. /** @hidden */
  20467. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20468. // Bounding info
  20469. this._updateBoundingInfo();
  20470. };
  20471. /**
  20472. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20473. * A mesh is in the frustum if its bounding box intersects the frustum
  20474. * @param frustumPlanes defines the frustum to test
  20475. * @returns true if the mesh is in the frustum planes
  20476. */
  20477. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20478. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20479. };
  20480. /**
  20481. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20482. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20483. * @param frustumPlanes defines the frustum to test
  20484. * @returns true if the mesh is completely in the frustum planes
  20485. */
  20486. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20487. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20488. };
  20489. /**
  20490. * True if the mesh intersects another mesh or a SolidParticle object
  20491. * @param mesh defines a target mesh or SolidParticle to test
  20492. * @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)
  20493. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20494. * @returns true if there is an intersection
  20495. */
  20496. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20497. if (precise === void 0) { precise = false; }
  20498. if (!this._boundingInfo || !mesh._boundingInfo) {
  20499. return false;
  20500. }
  20501. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20502. return true;
  20503. }
  20504. if (includeDescendants) {
  20505. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20506. var child = _a[_i];
  20507. if (child.intersectsMesh(mesh, precise, true)) {
  20508. return true;
  20509. }
  20510. }
  20511. }
  20512. return false;
  20513. };
  20514. /**
  20515. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20516. * @param point defines the point to test
  20517. * @returns true if there is an intersection
  20518. */
  20519. AbstractMesh.prototype.intersectsPoint = function (point) {
  20520. if (!this._boundingInfo) {
  20521. return false;
  20522. }
  20523. return this._boundingInfo.intersectsPoint(point);
  20524. };
  20525. /**
  20526. * Gets the current physics impostor
  20527. * @see http://doc.babylonjs.com/features/physics_engine
  20528. * @returns a physics impostor or null
  20529. */
  20530. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20531. return this.physicsImpostor;
  20532. };
  20533. /**
  20534. * Gets the position of the current mesh in camera space
  20535. * @param camera defines the camera to use
  20536. * @returns a position
  20537. */
  20538. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20539. if (camera === void 0) { camera = null; }
  20540. if (!camera) {
  20541. camera = this.getScene().activeCamera;
  20542. }
  20543. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20544. };
  20545. /**
  20546. * Returns the distance from the mesh to the active camera
  20547. * @param camera defines the camera to use
  20548. * @returns the distance
  20549. */
  20550. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20551. if (camera === void 0) { camera = null; }
  20552. if (!camera) {
  20553. camera = this.getScene().activeCamera;
  20554. }
  20555. return this.absolutePosition.subtract(camera.position).length();
  20556. };
  20557. /**
  20558. * Apply a physic impulse to the mesh
  20559. * @param force defines the force to apply
  20560. * @param contactPoint defines where to apply the force
  20561. * @returns the current mesh
  20562. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20563. */
  20564. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20565. if (!this.physicsImpostor) {
  20566. return this;
  20567. }
  20568. this.physicsImpostor.applyImpulse(force, contactPoint);
  20569. return this;
  20570. };
  20571. /**
  20572. * Creates a physic joint between two meshes
  20573. * @param otherMesh defines the other mesh to use
  20574. * @param pivot1 defines the pivot to use on this mesh
  20575. * @param pivot2 defines the pivot to use on the other mesh
  20576. * @param options defines additional options (can be plugin dependent)
  20577. * @returns the current mesh
  20578. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20579. */
  20580. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20581. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20582. return this;
  20583. }
  20584. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20585. mainPivot: pivot1,
  20586. connectedPivot: pivot2,
  20587. nativeParams: options
  20588. });
  20589. return this;
  20590. };
  20591. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20592. // Collisions
  20593. /**
  20594. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20595. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20596. */
  20597. get: function () {
  20598. return this._checkCollisions;
  20599. },
  20600. set: function (collisionEnabled) {
  20601. this._checkCollisions = collisionEnabled;
  20602. if (this.getScene().workerCollisions) {
  20603. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20604. }
  20605. },
  20606. enumerable: true,
  20607. configurable: true
  20608. });
  20609. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20610. /**
  20611. * Gets Collider object used to compute collisions (not physics)
  20612. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20613. */
  20614. get: function () {
  20615. return this._collider;
  20616. },
  20617. enumerable: true,
  20618. configurable: true
  20619. });
  20620. /**
  20621. * Move the mesh using collision engine
  20622. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20623. * @param displacement defines the requested displacement vector
  20624. * @returns the current mesh
  20625. */
  20626. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20627. var globalPosition = this.getAbsolutePosition();
  20628. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20629. if (!this._collider) {
  20630. this._collider = new BABYLON.Collider();
  20631. }
  20632. this._collider._radius = this.ellipsoid;
  20633. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20634. return this;
  20635. };
  20636. // Submeshes octree
  20637. /**
  20638. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20639. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20640. * @param maxCapacity defines the maximum size of each block (64 by default)
  20641. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20642. * @returns the new octree
  20643. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20644. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20645. */
  20646. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20647. if (maxCapacity === void 0) { maxCapacity = 64; }
  20648. if (maxDepth === void 0) { maxDepth = 2; }
  20649. if (!this._submeshesOctree) {
  20650. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20651. }
  20652. this.computeWorldMatrix(true);
  20653. var boundingInfo = this.getBoundingInfo();
  20654. // Update octree
  20655. var bbox = boundingInfo.boundingBox;
  20656. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20657. return this._submeshesOctree;
  20658. };
  20659. // Collisions
  20660. /** @hidden */
  20661. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20662. this._generatePointsArray();
  20663. if (!this._positions) {
  20664. return this;
  20665. }
  20666. // Transformation
  20667. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20668. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20669. subMesh._lastColliderWorldVertices = [];
  20670. subMesh._trianglePlanes = [];
  20671. var start = subMesh.verticesStart;
  20672. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20673. for (var i = start; i < end; i++) {
  20674. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20675. }
  20676. }
  20677. // Collide
  20678. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20679. if (collider.collisionFound) {
  20680. collider.collidedMesh = this;
  20681. }
  20682. return this;
  20683. };
  20684. /** @hidden */
  20685. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20686. var subMeshes;
  20687. var len;
  20688. // Octrees
  20689. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20690. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20691. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20692. len = intersections.length;
  20693. subMeshes = intersections.data;
  20694. }
  20695. else {
  20696. subMeshes = this.subMeshes;
  20697. len = subMeshes.length;
  20698. }
  20699. for (var index = 0; index < len; index++) {
  20700. var subMesh = subMeshes[index];
  20701. // Bounding test
  20702. if (len > 1 && !subMesh._checkCollision(collider))
  20703. continue;
  20704. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20705. }
  20706. return this;
  20707. };
  20708. /** @hidden */
  20709. AbstractMesh.prototype._checkCollision = function (collider) {
  20710. // Bounding box test
  20711. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20712. return this;
  20713. // Transformation matrix
  20714. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20715. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20716. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20717. return this;
  20718. };
  20719. // Picking
  20720. /** @hidden */
  20721. AbstractMesh.prototype._generatePointsArray = function () {
  20722. return false;
  20723. };
  20724. /**
  20725. * Checks if the passed Ray intersects with the mesh
  20726. * @param ray defines the ray to use
  20727. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20728. * @returns the picking info
  20729. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20730. */
  20731. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20732. var pickingInfo = new BABYLON.PickingInfo();
  20733. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20734. return pickingInfo;
  20735. }
  20736. if (!this._generatePointsArray()) {
  20737. return pickingInfo;
  20738. }
  20739. var intersectInfo = null;
  20740. // Octrees
  20741. var subMeshes;
  20742. var len;
  20743. if (this._submeshesOctree && this.useOctreeForPicking) {
  20744. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20745. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20746. len = intersections.length;
  20747. subMeshes = intersections.data;
  20748. }
  20749. else {
  20750. subMeshes = this.subMeshes;
  20751. len = subMeshes.length;
  20752. }
  20753. for (var index = 0; index < len; index++) {
  20754. var subMesh = subMeshes[index];
  20755. // Bounding test
  20756. if (len > 1 && !subMesh.canIntersects(ray))
  20757. continue;
  20758. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20759. if (currentIntersectInfo) {
  20760. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20761. intersectInfo = currentIntersectInfo;
  20762. intersectInfo.subMeshId = index;
  20763. if (fastCheck) {
  20764. break;
  20765. }
  20766. }
  20767. }
  20768. }
  20769. if (intersectInfo) {
  20770. // Get picked point
  20771. var world = this.getWorldMatrix();
  20772. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20773. var direction = ray.direction.clone();
  20774. direction = direction.scale(intersectInfo.distance);
  20775. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20776. var pickedPoint = worldOrigin.add(worldDirection);
  20777. // Return result
  20778. pickingInfo.hit = true;
  20779. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20780. pickingInfo.pickedPoint = pickedPoint;
  20781. pickingInfo.pickedMesh = this;
  20782. pickingInfo.bu = intersectInfo.bu || 0;
  20783. pickingInfo.bv = intersectInfo.bv || 0;
  20784. pickingInfo.faceId = intersectInfo.faceId;
  20785. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20786. return pickingInfo;
  20787. }
  20788. return pickingInfo;
  20789. };
  20790. /**
  20791. * Clones the current mesh
  20792. * @param name defines the mesh name
  20793. * @param newParent defines the new mesh parent
  20794. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20795. * @returns the new mesh
  20796. */
  20797. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20798. return null;
  20799. };
  20800. /**
  20801. * Disposes all the submeshes of the current meshnp
  20802. * @returns the current mesh
  20803. */
  20804. AbstractMesh.prototype.releaseSubMeshes = function () {
  20805. if (this.subMeshes) {
  20806. while (this.subMeshes.length) {
  20807. this.subMeshes[0].dispose();
  20808. }
  20809. }
  20810. else {
  20811. this.subMeshes = new Array();
  20812. }
  20813. return this;
  20814. };
  20815. /**
  20816. * Releases resources associated with this abstract mesh.
  20817. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20818. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20819. */
  20820. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20821. var _this = this;
  20822. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20823. var index;
  20824. // Smart Array Retainers.
  20825. this.getScene().freeActiveMeshes();
  20826. this.getScene().freeRenderingGroups();
  20827. // Action manager
  20828. if (this.actionManager !== undefined && this.actionManager !== null) {
  20829. this.actionManager.dispose();
  20830. this.actionManager = null;
  20831. }
  20832. // Skeleton
  20833. this._skeleton = null;
  20834. // Physics
  20835. if (this.physicsImpostor) {
  20836. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20837. }
  20838. // Intersections in progress
  20839. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20840. var other = this._intersectionsInProgress[index];
  20841. var pos = other._intersectionsInProgress.indexOf(this);
  20842. other._intersectionsInProgress.splice(pos, 1);
  20843. }
  20844. this._intersectionsInProgress = [];
  20845. // Lights
  20846. var lights = this.getScene().lights;
  20847. lights.forEach(function (light) {
  20848. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20849. if (meshIndex !== -1) {
  20850. light.includedOnlyMeshes.splice(meshIndex, 1);
  20851. }
  20852. meshIndex = light.excludedMeshes.indexOf(_this);
  20853. if (meshIndex !== -1) {
  20854. light.excludedMeshes.splice(meshIndex, 1);
  20855. }
  20856. // Shadow generators
  20857. var generator = light.getShadowGenerator();
  20858. if (generator) {
  20859. var shadowMap = generator.getShadowMap();
  20860. if (shadowMap && shadowMap.renderList) {
  20861. meshIndex = shadowMap.renderList.indexOf(_this);
  20862. if (meshIndex !== -1) {
  20863. shadowMap.renderList.splice(meshIndex, 1);
  20864. }
  20865. }
  20866. }
  20867. });
  20868. // Edges
  20869. if (this._edgesRenderer) {
  20870. this._edgesRenderer.dispose();
  20871. this._edgesRenderer = null;
  20872. }
  20873. // SubMeshes
  20874. if (this.getClassName() !== "InstancedMesh") {
  20875. this.releaseSubMeshes();
  20876. }
  20877. // Octree
  20878. var sceneOctree = this.getScene().selectionOctree;
  20879. if (sceneOctree !== undefined && sceneOctree !== null) {
  20880. var index = sceneOctree.dynamicContent.indexOf(this);
  20881. if (index !== -1) {
  20882. sceneOctree.dynamicContent.splice(index, 1);
  20883. }
  20884. }
  20885. // Query
  20886. var engine = this.getScene().getEngine();
  20887. if (this._occlusionQuery) {
  20888. this._isOcclusionQueryInProgress = false;
  20889. engine.deleteQuery(this._occlusionQuery);
  20890. this._occlusionQuery = null;
  20891. }
  20892. // Engine
  20893. engine.wipeCaches();
  20894. // Remove from scene
  20895. this.getScene().removeMesh(this);
  20896. if (disposeMaterialAndTextures) {
  20897. if (this.material) {
  20898. this.material.dispose(false, true);
  20899. }
  20900. }
  20901. if (!doNotRecurse) {
  20902. // Particles
  20903. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20904. if (this.getScene().particleSystems[index].emitter === this) {
  20905. this.getScene().particleSystems[index].dispose();
  20906. index--;
  20907. }
  20908. }
  20909. }
  20910. // facet data
  20911. if (this._facetDataEnabled) {
  20912. this.disableFacetData();
  20913. }
  20914. this.onAfterWorldMatrixUpdateObservable.clear();
  20915. this.onCollideObservable.clear();
  20916. this.onCollisionPositionChangeObservable.clear();
  20917. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20918. };
  20919. /**
  20920. * Adds the passed mesh as a child to the current mesh
  20921. * @param mesh defines the child mesh
  20922. * @returns the current mesh
  20923. */
  20924. AbstractMesh.prototype.addChild = function (mesh) {
  20925. mesh.setParent(this);
  20926. return this;
  20927. };
  20928. /**
  20929. * Removes the passed mesh from the current mesh children list
  20930. * @param mesh defines the child mesh
  20931. * @returns the current mesh
  20932. */
  20933. AbstractMesh.prototype.removeChild = function (mesh) {
  20934. mesh.setParent(null);
  20935. return this;
  20936. };
  20937. // Facet data
  20938. /** @hidden */
  20939. AbstractMesh.prototype._initFacetData = function () {
  20940. if (!this._facetNormals) {
  20941. this._facetNormals = new Array();
  20942. }
  20943. if (!this._facetPositions) {
  20944. this._facetPositions = new Array();
  20945. }
  20946. if (!this._facetPartitioning) {
  20947. this._facetPartitioning = new Array();
  20948. }
  20949. this._facetNb = (this.getIndices().length / 3) | 0;
  20950. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20951. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20952. for (var f = 0; f < this._facetNb; f++) {
  20953. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20954. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20955. }
  20956. this._facetDataEnabled = true;
  20957. return this;
  20958. };
  20959. /**
  20960. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20961. * This method can be called within the render loop.
  20962. * 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
  20963. * @returns the current mesh
  20964. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20965. */
  20966. AbstractMesh.prototype.updateFacetData = function () {
  20967. if (!this._facetDataEnabled) {
  20968. this._initFacetData();
  20969. }
  20970. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20971. var indices = this.getIndices();
  20972. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20973. var bInfo = this.getBoundingInfo();
  20974. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20975. // init arrays, matrix and sort function on first call
  20976. this._facetDepthSortEnabled = true;
  20977. if (indices instanceof Uint16Array) {
  20978. this._depthSortedIndices = new Uint16Array(indices);
  20979. }
  20980. else if (indices instanceof Uint32Array) {
  20981. this._depthSortedIndices = new Uint32Array(indices);
  20982. }
  20983. else {
  20984. var needs32bits = false;
  20985. for (var i = 0; i < indices.length; i++) {
  20986. if (indices[i] > 65535) {
  20987. needs32bits = true;
  20988. break;
  20989. }
  20990. }
  20991. if (needs32bits) {
  20992. this._depthSortedIndices = new Uint32Array(indices);
  20993. }
  20994. else {
  20995. this._depthSortedIndices = new Uint16Array(indices);
  20996. }
  20997. }
  20998. this._facetDepthSortFunction = function (f1, f2) {
  20999. return (f2.sqDistance - f1.sqDistance);
  21000. };
  21001. if (!this._facetDepthSortFrom) {
  21002. var camera = this.getScene().activeCamera;
  21003. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21004. }
  21005. this._depthSortedFacets = [];
  21006. for (var f = 0; f < this._facetNb; f++) {
  21007. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21008. this._depthSortedFacets.push(depthSortedFacet);
  21009. }
  21010. this._invertedMatrix = BABYLON.Matrix.Identity();
  21011. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21012. }
  21013. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21014. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21015. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21016. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21017. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21018. this._subDiv.max = this._partitioningSubdivisions;
  21019. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21020. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21021. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21022. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21023. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21024. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21025. // set the parameters for ComputeNormals()
  21026. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21027. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21028. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21029. this._facetParameters.bInfo = bInfo;
  21030. this._facetParameters.bbSize = this._bbSize;
  21031. this._facetParameters.subDiv = this._subDiv;
  21032. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21033. this._facetParameters.depthSort = this._facetDepthSort;
  21034. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21035. this.computeWorldMatrix(true);
  21036. this._worldMatrix.invertToRef(this._invertedMatrix);
  21037. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21038. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21039. }
  21040. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21041. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21042. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21043. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21044. var l = (this._depthSortedIndices.length / 3) | 0;
  21045. for (var f = 0; f < l; f++) {
  21046. var sind = this._depthSortedFacets[f].ind;
  21047. this._depthSortedIndices[f * 3] = indices[sind];
  21048. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21049. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21050. }
  21051. this.updateIndices(this._depthSortedIndices);
  21052. }
  21053. return this;
  21054. };
  21055. /**
  21056. * Returns the facetLocalNormals array.
  21057. * The normals are expressed in the mesh local spac
  21058. * @returns an array of Vector3
  21059. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21060. */
  21061. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21062. if (!this._facetNormals) {
  21063. this.updateFacetData();
  21064. }
  21065. return this._facetNormals;
  21066. };
  21067. /**
  21068. * Returns the facetLocalPositions array.
  21069. * The facet positions are expressed in the mesh local space
  21070. * @returns an array of Vector3
  21071. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21072. */
  21073. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21074. if (!this._facetPositions) {
  21075. this.updateFacetData();
  21076. }
  21077. return this._facetPositions;
  21078. };
  21079. /**
  21080. * Returns the facetLocalPartioning array
  21081. * @returns an array of array of numbers
  21082. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21083. */
  21084. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21085. if (!this._facetPartitioning) {
  21086. this.updateFacetData();
  21087. }
  21088. return this._facetPartitioning;
  21089. };
  21090. /**
  21091. * Returns the i-th facet position in the world system.
  21092. * This method allocates a new Vector3 per call
  21093. * @param i defines the facet index
  21094. * @returns a new Vector3
  21095. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21096. */
  21097. AbstractMesh.prototype.getFacetPosition = function (i) {
  21098. var pos = BABYLON.Vector3.Zero();
  21099. this.getFacetPositionToRef(i, pos);
  21100. return pos;
  21101. };
  21102. /**
  21103. * Sets the reference Vector3 with the i-th facet position in the world system
  21104. * @param i defines the facet index
  21105. * @param ref defines the target vector
  21106. * @returns the current mesh
  21107. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21108. */
  21109. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21110. var localPos = (this.getFacetLocalPositions())[i];
  21111. var world = this.getWorldMatrix();
  21112. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21113. return this;
  21114. };
  21115. /**
  21116. * Returns the i-th facet normal in the world system.
  21117. * This method allocates a new Vector3 per call
  21118. * @param i defines the facet index
  21119. * @returns a new Vector3
  21120. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21121. */
  21122. AbstractMesh.prototype.getFacetNormal = function (i) {
  21123. var norm = BABYLON.Vector3.Zero();
  21124. this.getFacetNormalToRef(i, norm);
  21125. return norm;
  21126. };
  21127. /**
  21128. * Sets the reference Vector3 with the i-th facet normal in the world system
  21129. * @param i defines the facet index
  21130. * @param ref defines the target vector
  21131. * @returns the current mesh
  21132. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21133. */
  21134. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21135. var localNorm = (this.getFacetLocalNormals())[i];
  21136. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21137. return this;
  21138. };
  21139. /**
  21140. * 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)
  21141. * @param x defines x coordinate
  21142. * @param y defines y coordinate
  21143. * @param z defines z coordinate
  21144. * @returns the array of facet indexes
  21145. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21146. */
  21147. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21148. var bInfo = this.getBoundingInfo();
  21149. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21150. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21151. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21152. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21153. return null;
  21154. }
  21155. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21156. };
  21157. /**
  21158. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21159. * @param projected sets as the (x,y,z) world projection on the facet
  21160. * @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
  21161. * @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
  21162. * @param x defines x coordinate
  21163. * @param y defines y coordinate
  21164. * @param z defines z coordinate
  21165. * @returns the face index if found (or null instead)
  21166. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21167. */
  21168. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21169. if (checkFace === void 0) { checkFace = false; }
  21170. if (facing === void 0) { facing = true; }
  21171. var world = this.getWorldMatrix();
  21172. var invMat = BABYLON.Tmp.Matrix[5];
  21173. world.invertToRef(invMat);
  21174. var invVect = BABYLON.Tmp.Vector3[8];
  21175. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21176. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21177. if (projected) {
  21178. // tranform the local computed projected vector to world coordinates
  21179. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21180. }
  21181. return closest;
  21182. };
  21183. /**
  21184. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21185. * @param projected sets as the (x,y,z) local projection on the facet
  21186. * @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
  21187. * @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
  21188. * @param x defines x coordinate
  21189. * @param y defines y coordinate
  21190. * @param z defines z coordinate
  21191. * @returns the face index if found (or null instead)
  21192. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21193. */
  21194. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21195. if (checkFace === void 0) { checkFace = false; }
  21196. if (facing === void 0) { facing = true; }
  21197. var closest = null;
  21198. var tmpx = 0.0;
  21199. var tmpy = 0.0;
  21200. var tmpz = 0.0;
  21201. var d = 0.0; // tmp dot facet normal * facet position
  21202. var t0 = 0.0;
  21203. var projx = 0.0;
  21204. var projy = 0.0;
  21205. var projz = 0.0;
  21206. // Get all the facets in the same partitioning block than (x, y, z)
  21207. var facetPositions = this.getFacetLocalPositions();
  21208. var facetNormals = this.getFacetLocalNormals();
  21209. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21210. if (!facetsInBlock) {
  21211. return null;
  21212. }
  21213. // Get the closest facet to (x, y, z)
  21214. var shortest = Number.MAX_VALUE; // init distance vars
  21215. var tmpDistance = shortest;
  21216. var fib; // current facet in the block
  21217. var norm; // current facet normal
  21218. var p0; // current facet barycenter position
  21219. // loop on all the facets in the current partitioning block
  21220. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21221. fib = facetsInBlock[idx];
  21222. norm = facetNormals[fib];
  21223. p0 = facetPositions[fib];
  21224. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21225. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21226. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21227. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21228. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21229. projx = x + norm.x * t0;
  21230. projy = y + norm.y * t0;
  21231. projz = z + norm.z * t0;
  21232. tmpx = projx - x;
  21233. tmpy = projy - y;
  21234. tmpz = projz - z;
  21235. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21236. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21237. shortest = tmpDistance;
  21238. closest = fib;
  21239. if (projected) {
  21240. projected.x = projx;
  21241. projected.y = projy;
  21242. projected.z = projz;
  21243. }
  21244. }
  21245. }
  21246. }
  21247. return closest;
  21248. };
  21249. /**
  21250. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21251. * @returns the parameters
  21252. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21253. */
  21254. AbstractMesh.prototype.getFacetDataParameters = function () {
  21255. return this._facetParameters;
  21256. };
  21257. /**
  21258. * Disables the feature FacetData and frees the related memory
  21259. * @returns the current mesh
  21260. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21261. */
  21262. AbstractMesh.prototype.disableFacetData = function () {
  21263. if (this._facetDataEnabled) {
  21264. this._facetDataEnabled = false;
  21265. this._facetPositions = new Array();
  21266. this._facetNormals = new Array();
  21267. this._facetPartitioning = new Array();
  21268. this._facetParameters = null;
  21269. this._depthSortedIndices = new Uint32Array(0);
  21270. }
  21271. return this;
  21272. };
  21273. /**
  21274. * Updates the AbstractMesh indices array
  21275. * @param indices defines the data source
  21276. * @returns the current mesh
  21277. */
  21278. AbstractMesh.prototype.updateIndices = function (indices) {
  21279. return this;
  21280. };
  21281. /**
  21282. * Creates new normals data for the mesh
  21283. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21284. * @returns the current mesh
  21285. */
  21286. AbstractMesh.prototype.createNormals = function (updatable) {
  21287. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21288. var indices = this.getIndices();
  21289. var normals;
  21290. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21291. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21292. }
  21293. else {
  21294. normals = [];
  21295. }
  21296. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21297. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21298. return this;
  21299. };
  21300. /**
  21301. * Align the mesh with a normal
  21302. * @param normal defines the normal to use
  21303. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21304. * @returns the current mesh
  21305. */
  21306. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21307. if (!upDirection) {
  21308. upDirection = BABYLON.Axis.Y;
  21309. }
  21310. var axisX = BABYLON.Tmp.Vector3[0];
  21311. var axisZ = BABYLON.Tmp.Vector3[1];
  21312. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21313. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21314. if (this.rotationQuaternion) {
  21315. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21316. }
  21317. else {
  21318. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21319. }
  21320. return this;
  21321. };
  21322. /** @hidden */
  21323. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21324. var engine = this.getEngine();
  21325. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21326. this._isOccluded = false;
  21327. return;
  21328. }
  21329. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21330. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21331. if (isOcclusionQueryAvailable) {
  21332. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21333. this._isOcclusionQueryInProgress = false;
  21334. this._occlusionInternalRetryCounter = 0;
  21335. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21336. }
  21337. else {
  21338. this._occlusionInternalRetryCounter++;
  21339. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21340. this._isOcclusionQueryInProgress = false;
  21341. this._occlusionInternalRetryCounter = 0;
  21342. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21343. // if strict continue the last state of the object.
  21344. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21345. }
  21346. else {
  21347. return;
  21348. }
  21349. }
  21350. }
  21351. // Todo. Move into an occlusion query component.
  21352. var scene = this.getScene();
  21353. if (scene.getBoundingBoxRenderer) {
  21354. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21355. if (!this._occlusionQuery) {
  21356. this._occlusionQuery = engine.createQuery();
  21357. }
  21358. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21359. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21360. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21361. this._isOcclusionQueryInProgress = true;
  21362. }
  21363. };
  21364. /** No occlusion */
  21365. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21366. /** Occlusion set to optimisitic */
  21367. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21368. /** Occlusion set to strict */
  21369. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21370. /** Use an accurante occlusion algorithm */
  21371. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21372. /** Use a conservative occlusion algorithm */
  21373. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21374. return AbstractMesh;
  21375. }(BABYLON.TransformNode));
  21376. BABYLON.AbstractMesh = AbstractMesh;
  21377. })(BABYLON || (BABYLON = {}));
  21378. //# sourceMappingURL=babylon.abstractMesh.js.map
  21379. var BABYLON;
  21380. (function (BABYLON) {
  21381. /**
  21382. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21383. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21384. * 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.
  21385. */
  21386. var Light = /** @class */ (function (_super) {
  21387. __extends(Light, _super);
  21388. /**
  21389. * Creates a Light object in the scene.
  21390. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21391. * @param name The firendly name of the light
  21392. * @param scene The scene the light belongs too
  21393. */
  21394. function Light(name, scene) {
  21395. var _this = _super.call(this, name, scene) || this;
  21396. /**
  21397. * Diffuse gives the basic color to an object.
  21398. */
  21399. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21400. /**
  21401. * Specular produces a highlight color on an object.
  21402. * Note: This is note affecting PBR materials.
  21403. */
  21404. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21405. /**
  21406. * Strength of the light.
  21407. * Note: By default it is define in the framework own unit.
  21408. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21409. */
  21410. _this.intensity = 1.0;
  21411. /**
  21412. * Defines how far from the source the light is impacting in scene units.
  21413. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21414. */
  21415. _this.range = Number.MAX_VALUE;
  21416. /**
  21417. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21418. * of light.
  21419. */
  21420. _this._photometricScale = 1.0;
  21421. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21422. _this._radius = 0.00001;
  21423. /**
  21424. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21425. * exceeding the number allowed of the materials.
  21426. */
  21427. _this.renderPriority = 0;
  21428. _this._shadowEnabled = true;
  21429. _this._excludeWithLayerMask = 0;
  21430. _this._includeOnlyWithLayerMask = 0;
  21431. _this._lightmapMode = 0;
  21432. /**
  21433. * @hidden Internal use only.
  21434. */
  21435. _this._excludedMeshesIds = new Array();
  21436. /**
  21437. * @hidden Internal use only.
  21438. */
  21439. _this._includedOnlyMeshesIds = new Array();
  21440. _this.getScene().addLight(_this);
  21441. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21442. _this._buildUniformLayout();
  21443. _this.includedOnlyMeshes = new Array();
  21444. _this.excludedMeshes = new Array();
  21445. _this._resyncMeshes();
  21446. return _this;
  21447. }
  21448. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21449. /**
  21450. * If every light affecting the material is in this lightmapMode,
  21451. * material.lightmapTexture adds or multiplies
  21452. * (depends on material.useLightmapAsShadowmap)
  21453. * after every other light calculations.
  21454. */
  21455. get: function () {
  21456. return Light._LIGHTMAP_DEFAULT;
  21457. },
  21458. enumerable: true,
  21459. configurable: true
  21460. });
  21461. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21462. /**
  21463. * material.lightmapTexture as only diffuse lighting from this light
  21464. * adds only specular lighting from this light
  21465. * adds dynamic shadows
  21466. */
  21467. get: function () {
  21468. return Light._LIGHTMAP_SPECULAR;
  21469. },
  21470. enumerable: true,
  21471. configurable: true
  21472. });
  21473. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21474. /**
  21475. * material.lightmapTexture as only lighting
  21476. * no light calculation from this light
  21477. * only adds dynamic shadows from this light
  21478. */
  21479. get: function () {
  21480. return Light._LIGHTMAP_SHADOWSONLY;
  21481. },
  21482. enumerable: true,
  21483. configurable: true
  21484. });
  21485. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21486. /**
  21487. * Each light type uses the default quantity according to its type:
  21488. * point/spot lights use luminous intensity
  21489. * directional lights use illuminance
  21490. */
  21491. get: function () {
  21492. return Light._INTENSITYMODE_AUTOMATIC;
  21493. },
  21494. enumerable: true,
  21495. configurable: true
  21496. });
  21497. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21498. /**
  21499. * lumen (lm)
  21500. */
  21501. get: function () {
  21502. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21503. },
  21504. enumerable: true,
  21505. configurable: true
  21506. });
  21507. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21508. /**
  21509. * candela (lm/sr)
  21510. */
  21511. get: function () {
  21512. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21513. },
  21514. enumerable: true,
  21515. configurable: true
  21516. });
  21517. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21518. /**
  21519. * lux (lm/m^2)
  21520. */
  21521. get: function () {
  21522. return Light._INTENSITYMODE_ILLUMINANCE;
  21523. },
  21524. enumerable: true,
  21525. configurable: true
  21526. });
  21527. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21528. /**
  21529. * nit (cd/m^2)
  21530. */
  21531. get: function () {
  21532. return Light._INTENSITYMODE_LUMINANCE;
  21533. },
  21534. enumerable: true,
  21535. configurable: true
  21536. });
  21537. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21538. /**
  21539. * Light type const id of the point light.
  21540. */
  21541. get: function () {
  21542. return Light._LIGHTTYPEID_POINTLIGHT;
  21543. },
  21544. enumerable: true,
  21545. configurable: true
  21546. });
  21547. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21548. /**
  21549. * Light type const id of the directional light.
  21550. */
  21551. get: function () {
  21552. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21553. },
  21554. enumerable: true,
  21555. configurable: true
  21556. });
  21557. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21558. /**
  21559. * Light type const id of the spot light.
  21560. */
  21561. get: function () {
  21562. return Light._LIGHTTYPEID_SPOTLIGHT;
  21563. },
  21564. enumerable: true,
  21565. configurable: true
  21566. });
  21567. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21568. /**
  21569. * Light type const id of the hemispheric light.
  21570. */
  21571. get: function () {
  21572. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21573. },
  21574. enumerable: true,
  21575. configurable: true
  21576. });
  21577. Object.defineProperty(Light.prototype, "intensityMode", {
  21578. /**
  21579. * Gets the photometric scale used to interpret the intensity.
  21580. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21581. */
  21582. get: function () {
  21583. return this._intensityMode;
  21584. },
  21585. /**
  21586. * Sets the photometric scale used to interpret the intensity.
  21587. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21588. */
  21589. set: function (value) {
  21590. this._intensityMode = value;
  21591. this._computePhotometricScale();
  21592. },
  21593. enumerable: true,
  21594. configurable: true
  21595. });
  21596. ;
  21597. ;
  21598. Object.defineProperty(Light.prototype, "radius", {
  21599. /**
  21600. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21601. */
  21602. get: function () {
  21603. return this._radius;
  21604. },
  21605. /**
  21606. * sets the light radius used by PBR Materials to simulate soft area lights.
  21607. */
  21608. set: function (value) {
  21609. this._radius = value;
  21610. this._computePhotometricScale();
  21611. },
  21612. enumerable: true,
  21613. configurable: true
  21614. });
  21615. ;
  21616. ;
  21617. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21618. /**
  21619. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21620. * the current shadow generator.
  21621. */
  21622. get: function () {
  21623. return this._shadowEnabled;
  21624. },
  21625. /**
  21626. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21627. * the current shadow generator.
  21628. */
  21629. set: function (value) {
  21630. if (this._shadowEnabled === value) {
  21631. return;
  21632. }
  21633. this._shadowEnabled = value;
  21634. this._markMeshesAsLightDirty();
  21635. },
  21636. enumerable: true,
  21637. configurable: true
  21638. });
  21639. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21640. /**
  21641. * Gets the only meshes impacted by this light.
  21642. */
  21643. get: function () {
  21644. return this._includedOnlyMeshes;
  21645. },
  21646. /**
  21647. * Sets the only meshes impacted by this light.
  21648. */
  21649. set: function (value) {
  21650. this._includedOnlyMeshes = value;
  21651. this._hookArrayForIncludedOnly(value);
  21652. },
  21653. enumerable: true,
  21654. configurable: true
  21655. });
  21656. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21657. /**
  21658. * Gets the meshes not impacted by this light.
  21659. */
  21660. get: function () {
  21661. return this._excludedMeshes;
  21662. },
  21663. /**
  21664. * Sets the meshes not impacted by this light.
  21665. */
  21666. set: function (value) {
  21667. this._excludedMeshes = value;
  21668. this._hookArrayForExcluded(value);
  21669. },
  21670. enumerable: true,
  21671. configurable: true
  21672. });
  21673. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21674. /**
  21675. * Gets the layer id use to find what meshes are not impacted by the light.
  21676. * Inactive if 0
  21677. */
  21678. get: function () {
  21679. return this._excludeWithLayerMask;
  21680. },
  21681. /**
  21682. * Sets the layer id use to find what meshes are not impacted by the light.
  21683. * Inactive if 0
  21684. */
  21685. set: function (value) {
  21686. this._excludeWithLayerMask = value;
  21687. this._resyncMeshes();
  21688. },
  21689. enumerable: true,
  21690. configurable: true
  21691. });
  21692. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21693. /**
  21694. * Gets the layer id use to find what meshes are impacted by the light.
  21695. * Inactive if 0
  21696. */
  21697. get: function () {
  21698. return this._includeOnlyWithLayerMask;
  21699. },
  21700. /**
  21701. * Sets the layer id use to find what meshes are impacted by the light.
  21702. * Inactive if 0
  21703. */
  21704. set: function (value) {
  21705. this._includeOnlyWithLayerMask = value;
  21706. this._resyncMeshes();
  21707. },
  21708. enumerable: true,
  21709. configurable: true
  21710. });
  21711. Object.defineProperty(Light.prototype, "lightmapMode", {
  21712. /**
  21713. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21714. */
  21715. get: function () {
  21716. return this._lightmapMode;
  21717. },
  21718. /**
  21719. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21720. */
  21721. set: function (value) {
  21722. if (this._lightmapMode === value) {
  21723. return;
  21724. }
  21725. this._lightmapMode = value;
  21726. this._markMeshesAsLightDirty();
  21727. },
  21728. enumerable: true,
  21729. configurable: true
  21730. });
  21731. /**
  21732. * Returns the string "Light".
  21733. * @returns the class name
  21734. */
  21735. Light.prototype.getClassName = function () {
  21736. return "Light";
  21737. };
  21738. /**
  21739. * Converts the light information to a readable string for debug purpose.
  21740. * @param fullDetails Supports for multiple levels of logging within scene loading
  21741. * @returns the human readable light info
  21742. */
  21743. Light.prototype.toString = function (fullDetails) {
  21744. var ret = "Name: " + this.name;
  21745. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21746. if (this.animations) {
  21747. for (var i = 0; i < this.animations.length; i++) {
  21748. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21749. }
  21750. }
  21751. if (fullDetails) {
  21752. }
  21753. return ret;
  21754. };
  21755. /**
  21756. * Set the enabled state of this node.
  21757. * @param value - the new enabled state
  21758. */
  21759. Light.prototype.setEnabled = function (value) {
  21760. _super.prototype.setEnabled.call(this, value);
  21761. this._resyncMeshes();
  21762. };
  21763. /**
  21764. * Returns the Light associated shadow generator if any.
  21765. * @return the associated shadow generator.
  21766. */
  21767. Light.prototype.getShadowGenerator = function () {
  21768. return this._shadowGenerator;
  21769. };
  21770. /**
  21771. * Returns a Vector3, the absolute light position in the World.
  21772. * @returns the world space position of the light
  21773. */
  21774. Light.prototype.getAbsolutePosition = function () {
  21775. return BABYLON.Vector3.Zero();
  21776. };
  21777. /**
  21778. * Specifies if the light will affect the passed mesh.
  21779. * @param mesh The mesh to test against the light
  21780. * @return true the mesh is affected otherwise, false.
  21781. */
  21782. Light.prototype.canAffectMesh = function (mesh) {
  21783. if (!mesh) {
  21784. return true;
  21785. }
  21786. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21787. return false;
  21788. }
  21789. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21790. return false;
  21791. }
  21792. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21793. return false;
  21794. }
  21795. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21796. return false;
  21797. }
  21798. return true;
  21799. };
  21800. /**
  21801. * Computes and Returns the light World matrix.
  21802. * @returns the world matrix
  21803. */
  21804. Light.prototype.getWorldMatrix = function () {
  21805. this._currentRenderId = this.getScene().getRenderId();
  21806. this._childRenderId = this._currentRenderId;
  21807. var worldMatrix = this._getWorldMatrix();
  21808. if (this.parent && this.parent.getWorldMatrix) {
  21809. if (!this._parentedWorldMatrix) {
  21810. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21811. }
  21812. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21813. this._markSyncedWithParent();
  21814. return this._parentedWorldMatrix;
  21815. }
  21816. return worldMatrix;
  21817. };
  21818. /**
  21819. * Sort function to order lights for rendering.
  21820. * @param a First Light object to compare to second.
  21821. * @param b Second Light object to compare first.
  21822. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21823. */
  21824. Light.CompareLightsPriority = function (a, b) {
  21825. //shadow-casting lights have priority over non-shadow-casting lights
  21826. //the renderPrioirty is a secondary sort criterion
  21827. if (a.shadowEnabled !== b.shadowEnabled) {
  21828. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21829. }
  21830. return b.renderPriority - a.renderPriority;
  21831. };
  21832. /**
  21833. * Releases resources associated with this node.
  21834. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21835. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21836. */
  21837. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21838. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21839. if (this._shadowGenerator) {
  21840. this._shadowGenerator.dispose();
  21841. this._shadowGenerator = null;
  21842. }
  21843. // Animations
  21844. this.getScene().stopAnimation(this);
  21845. // Remove from meshes
  21846. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21847. var mesh = _a[_i];
  21848. mesh._removeLightSource(this);
  21849. }
  21850. this._uniformBuffer.dispose();
  21851. // Remove from scene
  21852. this.getScene().removeLight(this);
  21853. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21854. };
  21855. /**
  21856. * Returns the light type ID (integer).
  21857. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21858. */
  21859. Light.prototype.getTypeID = function () {
  21860. return 0;
  21861. };
  21862. /**
  21863. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21864. * @returns the scaled intensity in intensity mode unit
  21865. */
  21866. Light.prototype.getScaledIntensity = function () {
  21867. return this._photometricScale * this.intensity;
  21868. };
  21869. /**
  21870. * Returns a new Light object, named "name", from the current one.
  21871. * @param name The name of the cloned light
  21872. * @returns the new created light
  21873. */
  21874. Light.prototype.clone = function (name) {
  21875. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21876. if (!constructor) {
  21877. return null;
  21878. }
  21879. return BABYLON.SerializationHelper.Clone(constructor, this);
  21880. };
  21881. /**
  21882. * Serializes the current light into a Serialization object.
  21883. * @returns the serialized object.
  21884. */
  21885. Light.prototype.serialize = function () {
  21886. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21887. // Type
  21888. serializationObject.type = this.getTypeID();
  21889. // Parent
  21890. if (this.parent) {
  21891. serializationObject.parentId = this.parent.id;
  21892. }
  21893. // Inclusion / exclusions
  21894. if (this.excludedMeshes.length > 0) {
  21895. serializationObject.excludedMeshesIds = [];
  21896. this.excludedMeshes.forEach(function (mesh) {
  21897. serializationObject.excludedMeshesIds.push(mesh.id);
  21898. });
  21899. }
  21900. if (this.includedOnlyMeshes.length > 0) {
  21901. serializationObject.includedOnlyMeshesIds = [];
  21902. this.includedOnlyMeshes.forEach(function (mesh) {
  21903. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21904. });
  21905. }
  21906. // Animations
  21907. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21908. serializationObject.ranges = this.serializeAnimationRanges();
  21909. return serializationObject;
  21910. };
  21911. /**
  21912. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21913. * This new light is named "name" and added to the passed scene.
  21914. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21915. * @param name The friendly name of the light
  21916. * @param scene The scene the new light will belong to
  21917. * @returns the constructor function
  21918. */
  21919. Light.GetConstructorFromName = function (type, name, scene) {
  21920. switch (type) {
  21921. case 0:
  21922. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21923. case 1:
  21924. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21925. case 2:
  21926. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21927. case 3:
  21928. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21929. }
  21930. return null;
  21931. };
  21932. /**
  21933. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21934. * @param parsedLight The JSON representation of the light
  21935. * @param scene The scene to create the parsed light in
  21936. * @returns the created light after parsing
  21937. */
  21938. Light.Parse = function (parsedLight, scene) {
  21939. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21940. if (!constructor) {
  21941. return null;
  21942. }
  21943. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21944. // Inclusion / exclusions
  21945. if (parsedLight.excludedMeshesIds) {
  21946. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21947. }
  21948. if (parsedLight.includedOnlyMeshesIds) {
  21949. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21950. }
  21951. // Parent
  21952. if (parsedLight.parentId) {
  21953. light._waitingParentId = parsedLight.parentId;
  21954. }
  21955. // Animations
  21956. if (parsedLight.animations) {
  21957. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21958. var parsedAnimation = parsedLight.animations[animationIndex];
  21959. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21960. }
  21961. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21962. }
  21963. if (parsedLight.autoAnimate) {
  21964. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21965. }
  21966. return light;
  21967. };
  21968. Light.prototype._hookArrayForExcluded = function (array) {
  21969. var _this = this;
  21970. var oldPush = array.push;
  21971. array.push = function () {
  21972. var items = [];
  21973. for (var _i = 0; _i < arguments.length; _i++) {
  21974. items[_i] = arguments[_i];
  21975. }
  21976. var result = oldPush.apply(array, items);
  21977. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21978. var item = items_1[_a];
  21979. item._resyncLighSource(_this);
  21980. }
  21981. return result;
  21982. };
  21983. var oldSplice = array.splice;
  21984. array.splice = function (index, deleteCount) {
  21985. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21986. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21987. var item = deleted_1[_i];
  21988. item._resyncLighSource(_this);
  21989. }
  21990. return deleted;
  21991. };
  21992. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21993. var item = array_1[_i];
  21994. item._resyncLighSource(this);
  21995. }
  21996. };
  21997. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21998. var _this = this;
  21999. var oldPush = array.push;
  22000. array.push = function () {
  22001. var items = [];
  22002. for (var _i = 0; _i < arguments.length; _i++) {
  22003. items[_i] = arguments[_i];
  22004. }
  22005. var result = oldPush.apply(array, items);
  22006. _this._resyncMeshes();
  22007. return result;
  22008. };
  22009. var oldSplice = array.splice;
  22010. array.splice = function (index, deleteCount) {
  22011. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22012. _this._resyncMeshes();
  22013. return deleted;
  22014. };
  22015. this._resyncMeshes();
  22016. };
  22017. Light.prototype._resyncMeshes = function () {
  22018. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22019. var mesh = _a[_i];
  22020. mesh._resyncLighSource(this);
  22021. }
  22022. };
  22023. /**
  22024. * Forces the meshes to update their light related information in their rendering used effects
  22025. * @hidden Internal Use Only
  22026. */
  22027. Light.prototype._markMeshesAsLightDirty = function () {
  22028. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22029. var mesh = _a[_i];
  22030. if (mesh._lightSources.indexOf(this) !== -1) {
  22031. mesh._markSubMeshesAsLightDirty();
  22032. }
  22033. }
  22034. };
  22035. /**
  22036. * Recomputes the cached photometric scale if needed.
  22037. */
  22038. Light.prototype._computePhotometricScale = function () {
  22039. this._photometricScale = this._getPhotometricScale();
  22040. this.getScene().resetCachedMaterial();
  22041. };
  22042. /**
  22043. * Returns the Photometric Scale according to the light type and intensity mode.
  22044. */
  22045. Light.prototype._getPhotometricScale = function () {
  22046. var photometricScale = 0.0;
  22047. var lightTypeID = this.getTypeID();
  22048. //get photometric mode
  22049. var photometricMode = this.intensityMode;
  22050. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22051. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22052. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22053. }
  22054. else {
  22055. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22056. }
  22057. }
  22058. //compute photometric scale
  22059. switch (lightTypeID) {
  22060. case Light.LIGHTTYPEID_POINTLIGHT:
  22061. case Light.LIGHTTYPEID_SPOTLIGHT:
  22062. switch (photometricMode) {
  22063. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22064. photometricScale = 1.0 / (4.0 * Math.PI);
  22065. break;
  22066. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22067. photometricScale = 1.0;
  22068. break;
  22069. case Light.INTENSITYMODE_LUMINANCE:
  22070. photometricScale = this.radius * this.radius;
  22071. break;
  22072. }
  22073. break;
  22074. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22075. switch (photometricMode) {
  22076. case Light.INTENSITYMODE_ILLUMINANCE:
  22077. photometricScale = 1.0;
  22078. break;
  22079. case Light.INTENSITYMODE_LUMINANCE:
  22080. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22081. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22082. var apexAngleRadians = this.radius;
  22083. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22084. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22085. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22086. photometricScale = solidAngle;
  22087. break;
  22088. }
  22089. break;
  22090. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22091. // No fall off in hemisperic light.
  22092. photometricScale = 1.0;
  22093. break;
  22094. }
  22095. return photometricScale;
  22096. };
  22097. /**
  22098. * Reorder the light in the scene according to their defined priority.
  22099. * @hidden Internal Use Only
  22100. */
  22101. Light.prototype._reorderLightsInScene = function () {
  22102. var scene = this.getScene();
  22103. if (this._renderPriority != 0) {
  22104. scene.requireLightSorting = true;
  22105. }
  22106. this.getScene().sortLightsByPriority();
  22107. };
  22108. //lightmapMode Consts
  22109. Light._LIGHTMAP_DEFAULT = 0;
  22110. Light._LIGHTMAP_SPECULAR = 1;
  22111. Light._LIGHTMAP_SHADOWSONLY = 2;
  22112. // Intensity Mode Consts
  22113. Light._INTENSITYMODE_AUTOMATIC = 0;
  22114. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22115. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22116. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22117. Light._INTENSITYMODE_LUMINANCE = 4;
  22118. // Light types ids const.
  22119. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22120. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22121. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22122. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22123. __decorate([
  22124. BABYLON.serializeAsColor3()
  22125. ], Light.prototype, "diffuse", void 0);
  22126. __decorate([
  22127. BABYLON.serializeAsColor3()
  22128. ], Light.prototype, "specular", void 0);
  22129. __decorate([
  22130. BABYLON.serialize()
  22131. ], Light.prototype, "intensity", void 0);
  22132. __decorate([
  22133. BABYLON.serialize()
  22134. ], Light.prototype, "range", void 0);
  22135. __decorate([
  22136. BABYLON.serialize()
  22137. ], Light.prototype, "intensityMode", null);
  22138. __decorate([
  22139. BABYLON.serialize()
  22140. ], Light.prototype, "radius", null);
  22141. __decorate([
  22142. BABYLON.serialize()
  22143. ], Light.prototype, "_renderPriority", void 0);
  22144. __decorate([
  22145. BABYLON.expandToProperty("_reorderLightsInScene")
  22146. ], Light.prototype, "renderPriority", void 0);
  22147. __decorate([
  22148. BABYLON.serialize("shadowEnabled")
  22149. ], Light.prototype, "_shadowEnabled", void 0);
  22150. __decorate([
  22151. BABYLON.serialize("excludeWithLayerMask")
  22152. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22153. __decorate([
  22154. BABYLON.serialize("includeOnlyWithLayerMask")
  22155. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22156. __decorate([
  22157. BABYLON.serialize("lightmapMode")
  22158. ], Light.prototype, "_lightmapMode", void 0);
  22159. return Light;
  22160. }(BABYLON.Node));
  22161. BABYLON.Light = Light;
  22162. })(BABYLON || (BABYLON = {}));
  22163. //# sourceMappingURL=babylon.light.js.map
  22164. var BABYLON;
  22165. (function (BABYLON) {
  22166. var Camera = /** @class */ (function (_super) {
  22167. __extends(Camera, _super);
  22168. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22169. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22170. var _this = _super.call(this, name, scene) || this;
  22171. /**
  22172. * The vector the camera should consider as up.
  22173. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22174. */
  22175. _this.upVector = BABYLON.Vector3.Up();
  22176. _this.orthoLeft = null;
  22177. _this.orthoRight = null;
  22178. _this.orthoBottom = null;
  22179. _this.orthoTop = null;
  22180. /**
  22181. * FOV is set in Radians. (default is 0.8)
  22182. */
  22183. _this.fov = 0.8;
  22184. _this.minZ = 1;
  22185. _this.maxZ = 10000.0;
  22186. _this.inertia = 0.9;
  22187. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22188. _this.isIntermediate = false;
  22189. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22190. /**
  22191. * Restricts the camera to viewing objects with the same layerMask.
  22192. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22193. */
  22194. _this.layerMask = 0x0FFFFFFF;
  22195. /**
  22196. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22197. */
  22198. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22199. // Camera rig members
  22200. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22201. _this._rigCameras = new Array();
  22202. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22203. _this._skipRendering = false;
  22204. _this.customRenderTargets = new Array();
  22205. // Observables
  22206. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22207. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22208. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22209. _this.onRestoreStateObservable = new BABYLON.Observable();
  22210. // Cache
  22211. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22212. _this._projectionMatrix = new BABYLON.Matrix();
  22213. _this._doNotComputeProjectionMatrix = false;
  22214. _this._worldMatrix = BABYLON.Matrix.Identity();
  22215. _this._postProcesses = new Array();
  22216. _this._transformMatrix = BABYLON.Matrix.Zero();
  22217. _this._activeMeshes = new BABYLON.SmartArray(256);
  22218. _this._globalPosition = BABYLON.Vector3.Zero();
  22219. _this._refreshFrustumPlanes = true;
  22220. _this.getScene().addCamera(_this);
  22221. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22222. _this.getScene().activeCamera = _this;
  22223. }
  22224. _this.position = position;
  22225. return _this;
  22226. }
  22227. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22228. get: function () {
  22229. return Camera._PERSPECTIVE_CAMERA;
  22230. },
  22231. enumerable: true,
  22232. configurable: true
  22233. });
  22234. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22235. get: function () {
  22236. return Camera._ORTHOGRAPHIC_CAMERA;
  22237. },
  22238. enumerable: true,
  22239. configurable: true
  22240. });
  22241. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22242. /**
  22243. * This is the default FOV mode for perspective cameras.
  22244. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22245. *
  22246. */
  22247. get: function () {
  22248. return Camera._FOVMODE_VERTICAL_FIXED;
  22249. },
  22250. enumerable: true,
  22251. configurable: true
  22252. });
  22253. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22254. /**
  22255. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22256. *
  22257. */
  22258. get: function () {
  22259. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22260. },
  22261. enumerable: true,
  22262. configurable: true
  22263. });
  22264. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22265. get: function () {
  22266. return Camera._RIG_MODE_NONE;
  22267. },
  22268. enumerable: true,
  22269. configurable: true
  22270. });
  22271. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22272. get: function () {
  22273. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22274. },
  22275. enumerable: true,
  22276. configurable: true
  22277. });
  22278. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22279. get: function () {
  22280. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22281. },
  22282. enumerable: true,
  22283. configurable: true
  22284. });
  22285. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22286. get: function () {
  22287. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22288. },
  22289. enumerable: true,
  22290. configurable: true
  22291. });
  22292. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22293. get: function () {
  22294. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22295. },
  22296. enumerable: true,
  22297. configurable: true
  22298. });
  22299. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22300. get: function () {
  22301. return Camera._RIG_MODE_VR;
  22302. },
  22303. enumerable: true,
  22304. configurable: true
  22305. });
  22306. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22307. get: function () {
  22308. return Camera._RIG_MODE_WEBVR;
  22309. },
  22310. enumerable: true,
  22311. configurable: true
  22312. });
  22313. /**
  22314. * Store current camera state (fov, position, etc..)
  22315. */
  22316. Camera.prototype.storeState = function () {
  22317. this._stateStored = true;
  22318. this._storedFov = this.fov;
  22319. return this;
  22320. };
  22321. /**
  22322. * Restores the camera state values if it has been stored. You must call storeState() first
  22323. */
  22324. Camera.prototype._restoreStateValues = function () {
  22325. if (!this._stateStored) {
  22326. return false;
  22327. }
  22328. this.fov = this._storedFov;
  22329. return true;
  22330. };
  22331. /**
  22332. * Restored camera state. You must call storeState() first
  22333. */
  22334. Camera.prototype.restoreState = function () {
  22335. if (this._restoreStateValues()) {
  22336. this.onRestoreStateObservable.notifyObservers(this);
  22337. return true;
  22338. }
  22339. return false;
  22340. };
  22341. Camera.prototype.getClassName = function () {
  22342. return "Camera";
  22343. };
  22344. /**
  22345. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22346. */
  22347. Camera.prototype.toString = function (fullDetails) {
  22348. var ret = "Name: " + this.name;
  22349. ret += ", type: " + this.getClassName();
  22350. if (this.animations) {
  22351. for (var i = 0; i < this.animations.length; i++) {
  22352. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22353. }
  22354. }
  22355. if (fullDetails) {
  22356. }
  22357. return ret;
  22358. };
  22359. Object.defineProperty(Camera.prototype, "globalPosition", {
  22360. get: function () {
  22361. return this._globalPosition;
  22362. },
  22363. enumerable: true,
  22364. configurable: true
  22365. });
  22366. Camera.prototype.getActiveMeshes = function () {
  22367. return this._activeMeshes;
  22368. };
  22369. Camera.prototype.isActiveMesh = function (mesh) {
  22370. return (this._activeMeshes.indexOf(mesh) !== -1);
  22371. };
  22372. /**
  22373. * Is this camera ready to be used/rendered
  22374. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22375. * @return true if the camera is ready
  22376. */
  22377. Camera.prototype.isReady = function (completeCheck) {
  22378. if (completeCheck === void 0) { completeCheck = false; }
  22379. if (completeCheck) {
  22380. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22381. var pp = _a[_i];
  22382. if (pp && !pp.isReady()) {
  22383. return false;
  22384. }
  22385. }
  22386. }
  22387. return _super.prototype.isReady.call(this, completeCheck);
  22388. };
  22389. //Cache
  22390. Camera.prototype._initCache = function () {
  22391. _super.prototype._initCache.call(this);
  22392. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22393. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22394. this._cache.mode = undefined;
  22395. this._cache.minZ = undefined;
  22396. this._cache.maxZ = undefined;
  22397. this._cache.fov = undefined;
  22398. this._cache.fovMode = undefined;
  22399. this._cache.aspectRatio = undefined;
  22400. this._cache.orthoLeft = undefined;
  22401. this._cache.orthoRight = undefined;
  22402. this._cache.orthoBottom = undefined;
  22403. this._cache.orthoTop = undefined;
  22404. this._cache.renderWidth = undefined;
  22405. this._cache.renderHeight = undefined;
  22406. };
  22407. Camera.prototype._updateCache = function (ignoreParentClass) {
  22408. if (!ignoreParentClass) {
  22409. _super.prototype._updateCache.call(this);
  22410. }
  22411. this._cache.position.copyFrom(this.position);
  22412. this._cache.upVector.copyFrom(this.upVector);
  22413. };
  22414. // Synchronized
  22415. Camera.prototype._isSynchronized = function () {
  22416. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22417. };
  22418. Camera.prototype._isSynchronizedViewMatrix = function () {
  22419. if (!_super.prototype._isSynchronized.call(this))
  22420. return false;
  22421. return this._cache.position.equals(this.position)
  22422. && this._cache.upVector.equals(this.upVector)
  22423. && this.isSynchronizedWithParent();
  22424. };
  22425. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22426. var check = this._cache.mode === this.mode
  22427. && this._cache.minZ === this.minZ
  22428. && this._cache.maxZ === this.maxZ;
  22429. if (!check) {
  22430. return false;
  22431. }
  22432. var engine = this.getEngine();
  22433. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22434. check = this._cache.fov === this.fov
  22435. && this._cache.fovMode === this.fovMode
  22436. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22437. }
  22438. else {
  22439. check = this._cache.orthoLeft === this.orthoLeft
  22440. && this._cache.orthoRight === this.orthoRight
  22441. && this._cache.orthoBottom === this.orthoBottom
  22442. && this._cache.orthoTop === this.orthoTop
  22443. && this._cache.renderWidth === engine.getRenderWidth()
  22444. && this._cache.renderHeight === engine.getRenderHeight();
  22445. }
  22446. return check;
  22447. };
  22448. // Controls
  22449. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22450. };
  22451. Camera.prototype.detachControl = function (element) {
  22452. };
  22453. Camera.prototype.update = function () {
  22454. this._checkInputs();
  22455. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22456. this._updateRigCameras();
  22457. }
  22458. };
  22459. Camera.prototype._checkInputs = function () {
  22460. this.onAfterCheckInputsObservable.notifyObservers(this);
  22461. };
  22462. Object.defineProperty(Camera.prototype, "rigCameras", {
  22463. get: function () {
  22464. return this._rigCameras;
  22465. },
  22466. enumerable: true,
  22467. configurable: true
  22468. });
  22469. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22470. get: function () {
  22471. return this._rigPostProcess;
  22472. },
  22473. enumerable: true,
  22474. configurable: true
  22475. });
  22476. /**
  22477. * Internal, gets the first post proces.
  22478. * @returns the first post process to be run on this camera.
  22479. */
  22480. Camera.prototype._getFirstPostProcess = function () {
  22481. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22482. if (this._postProcesses[ppIndex] !== null) {
  22483. return this._postProcesses[ppIndex];
  22484. }
  22485. }
  22486. return null;
  22487. };
  22488. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22489. // invalidate framebuffer
  22490. var firstPostProcess = this._getFirstPostProcess();
  22491. if (firstPostProcess) {
  22492. firstPostProcess.markTextureDirty();
  22493. }
  22494. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22495. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22496. var cam = this._rigCameras[i];
  22497. var rigPostProcess = cam._rigPostProcess;
  22498. // for VR rig, there does not have to be a post process
  22499. if (rigPostProcess) {
  22500. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22501. if (isPass) {
  22502. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22503. cam.isIntermediate = this._postProcesses.length === 0;
  22504. }
  22505. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22506. rigPostProcess.markTextureDirty();
  22507. }
  22508. else {
  22509. cam._postProcesses = this._postProcesses.slice(0);
  22510. }
  22511. }
  22512. };
  22513. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22514. if (insertAt === void 0) { insertAt = null; }
  22515. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22516. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22517. return 0;
  22518. }
  22519. if (insertAt == null || insertAt < 0) {
  22520. this._postProcesses.push(postProcess);
  22521. }
  22522. else if (this._postProcesses[insertAt] === null) {
  22523. this._postProcesses[insertAt] = postProcess;
  22524. }
  22525. else {
  22526. this._postProcesses.splice(insertAt, 0, postProcess);
  22527. }
  22528. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22529. return this._postProcesses.indexOf(postProcess);
  22530. };
  22531. Camera.prototype.detachPostProcess = function (postProcess) {
  22532. var idx = this._postProcesses.indexOf(postProcess);
  22533. if (idx !== -1) {
  22534. this._postProcesses[idx] = null;
  22535. }
  22536. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22537. };
  22538. Camera.prototype.getWorldMatrix = function () {
  22539. if (this._isSynchronizedViewMatrix()) {
  22540. return this._worldMatrix;
  22541. }
  22542. // Getting the the view matrix will also compute the world matrix.
  22543. this.getViewMatrix();
  22544. return this._worldMatrix;
  22545. };
  22546. Camera.prototype._getViewMatrix = function () {
  22547. return BABYLON.Matrix.Identity();
  22548. };
  22549. Camera.prototype.getViewMatrix = function (force) {
  22550. if (!force && this._isSynchronizedViewMatrix()) {
  22551. return this._computedViewMatrix;
  22552. }
  22553. this.updateCache();
  22554. this._computedViewMatrix = this._getViewMatrix();
  22555. this._currentRenderId = this.getScene().getRenderId();
  22556. this._childRenderId = this._currentRenderId;
  22557. this._refreshFrustumPlanes = true;
  22558. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22559. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22560. }
  22561. this.onViewMatrixChangedObservable.notifyObservers(this);
  22562. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22563. return this._computedViewMatrix;
  22564. };
  22565. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22566. this._doNotComputeProjectionMatrix = true;
  22567. if (projection !== undefined) {
  22568. this._projectionMatrix = projection;
  22569. }
  22570. };
  22571. ;
  22572. Camera.prototype.unfreezeProjectionMatrix = function () {
  22573. this._doNotComputeProjectionMatrix = false;
  22574. };
  22575. ;
  22576. Camera.prototype.getProjectionMatrix = function (force) {
  22577. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22578. return this._projectionMatrix;
  22579. }
  22580. // Cache
  22581. this._cache.mode = this.mode;
  22582. this._cache.minZ = this.minZ;
  22583. this._cache.maxZ = this.maxZ;
  22584. // Matrix
  22585. this._refreshFrustumPlanes = true;
  22586. var engine = this.getEngine();
  22587. var scene = this.getScene();
  22588. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22589. this._cache.fov = this.fov;
  22590. this._cache.fovMode = this.fovMode;
  22591. this._cache.aspectRatio = engine.getAspectRatio(this);
  22592. if (this.minZ <= 0) {
  22593. this.minZ = 0.1;
  22594. }
  22595. if (scene.useRightHandedSystem) {
  22596. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22597. }
  22598. else {
  22599. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22600. }
  22601. }
  22602. else {
  22603. var halfWidth = engine.getRenderWidth() / 2.0;
  22604. var halfHeight = engine.getRenderHeight() / 2.0;
  22605. if (scene.useRightHandedSystem) {
  22606. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22607. }
  22608. else {
  22609. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22610. }
  22611. this._cache.orthoLeft = this.orthoLeft;
  22612. this._cache.orthoRight = this.orthoRight;
  22613. this._cache.orthoBottom = this.orthoBottom;
  22614. this._cache.orthoTop = this.orthoTop;
  22615. this._cache.renderWidth = engine.getRenderWidth();
  22616. this._cache.renderHeight = engine.getRenderHeight();
  22617. }
  22618. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22619. return this._projectionMatrix;
  22620. };
  22621. Camera.prototype.getTranformationMatrix = function () {
  22622. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22623. return this._transformMatrix;
  22624. };
  22625. Camera.prototype.updateFrustumPlanes = function () {
  22626. if (!this._refreshFrustumPlanes) {
  22627. return;
  22628. }
  22629. this.getTranformationMatrix();
  22630. if (!this._frustumPlanes) {
  22631. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22632. }
  22633. else {
  22634. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22635. }
  22636. this._refreshFrustumPlanes = false;
  22637. };
  22638. Camera.prototype.isInFrustum = function (target) {
  22639. this.updateFrustumPlanes();
  22640. return target.isInFrustum(this._frustumPlanes);
  22641. };
  22642. Camera.prototype.isCompletelyInFrustum = function (target) {
  22643. this.updateFrustumPlanes();
  22644. return target.isCompletelyInFrustum(this._frustumPlanes);
  22645. };
  22646. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22647. if (length === void 0) { length = 100; }
  22648. if (!transform) {
  22649. transform = this.getWorldMatrix();
  22650. }
  22651. if (!origin) {
  22652. origin = this.position;
  22653. }
  22654. var forward = new BABYLON.Vector3(0, 0, 1);
  22655. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22656. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22657. return new BABYLON.Ray(origin, direction, length);
  22658. };
  22659. /**
  22660. * Releases resources associated with this node.
  22661. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22662. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22663. */
  22664. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22665. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22666. // Observables
  22667. this.onViewMatrixChangedObservable.clear();
  22668. this.onProjectionMatrixChangedObservable.clear();
  22669. this.onAfterCheckInputsObservable.clear();
  22670. this.onRestoreStateObservable.clear();
  22671. // Inputs
  22672. if (this.inputs) {
  22673. this.inputs.clear();
  22674. }
  22675. // Animations
  22676. this.getScene().stopAnimation(this);
  22677. // Remove from scene
  22678. this.getScene().removeCamera(this);
  22679. while (this._rigCameras.length > 0) {
  22680. var camera = this._rigCameras.pop();
  22681. if (camera) {
  22682. camera.dispose();
  22683. }
  22684. }
  22685. // Postprocesses
  22686. if (this._rigPostProcess) {
  22687. this._rigPostProcess.dispose(this);
  22688. this._rigPostProcess = null;
  22689. this._postProcesses = [];
  22690. }
  22691. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22692. this._rigPostProcess = null;
  22693. this._postProcesses = [];
  22694. }
  22695. else {
  22696. var i = this._postProcesses.length;
  22697. while (--i >= 0) {
  22698. var postProcess = this._postProcesses[i];
  22699. if (postProcess) {
  22700. postProcess.dispose(this);
  22701. }
  22702. }
  22703. }
  22704. // Render targets
  22705. var i = this.customRenderTargets.length;
  22706. while (--i >= 0) {
  22707. this.customRenderTargets[i].dispose();
  22708. }
  22709. this.customRenderTargets = [];
  22710. // Active Meshes
  22711. this._activeMeshes.dispose();
  22712. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22713. };
  22714. Object.defineProperty(Camera.prototype, "leftCamera", {
  22715. // ---- Camera rigs section ----
  22716. get: function () {
  22717. if (this._rigCameras.length < 1) {
  22718. return null;
  22719. }
  22720. return this._rigCameras[0];
  22721. },
  22722. enumerable: true,
  22723. configurable: true
  22724. });
  22725. Object.defineProperty(Camera.prototype, "rightCamera", {
  22726. get: function () {
  22727. if (this._rigCameras.length < 2) {
  22728. return null;
  22729. }
  22730. return this._rigCameras[1];
  22731. },
  22732. enumerable: true,
  22733. configurable: true
  22734. });
  22735. Camera.prototype.getLeftTarget = function () {
  22736. if (this._rigCameras.length < 1) {
  22737. return null;
  22738. }
  22739. return this._rigCameras[0].getTarget();
  22740. };
  22741. Camera.prototype.getRightTarget = function () {
  22742. if (this._rigCameras.length < 2) {
  22743. return null;
  22744. }
  22745. return this._rigCameras[1].getTarget();
  22746. };
  22747. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22748. if (this.cameraRigMode === mode) {
  22749. return;
  22750. }
  22751. while (this._rigCameras.length > 0) {
  22752. var camera = this._rigCameras.pop();
  22753. if (camera) {
  22754. camera.dispose();
  22755. }
  22756. }
  22757. this.cameraRigMode = mode;
  22758. this._cameraRigParams = {};
  22759. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22760. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22761. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22762. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22763. // create the rig cameras, unless none
  22764. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22765. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22766. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22767. if (leftCamera && rightCamera) {
  22768. this._rigCameras.push(leftCamera);
  22769. this._rigCameras.push(rightCamera);
  22770. }
  22771. }
  22772. switch (this.cameraRigMode) {
  22773. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22774. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22775. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22776. break;
  22777. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22778. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22779. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22780. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22781. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22782. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22783. break;
  22784. case Camera.RIG_MODE_VR:
  22785. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22786. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22787. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22788. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22789. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22790. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22791. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22792. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22793. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22794. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22795. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22796. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22797. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22798. if (metrics.compensateDistortion) {
  22799. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22800. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22801. }
  22802. break;
  22803. case Camera.RIG_MODE_WEBVR:
  22804. if (rigParams.vrDisplay) {
  22805. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22806. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22807. //Left eye
  22808. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22809. this._rigCameras[0].setCameraRigParameter("left", true);
  22810. //leaving this for future reference
  22811. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22812. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22813. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22814. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22815. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22816. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22817. this._rigCameras[0].parent = this;
  22818. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22819. //Right eye
  22820. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22821. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22822. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22823. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22824. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22825. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22826. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22827. this._rigCameras[1].parent = this;
  22828. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22829. if (Camera.UseAlternateWebVRRendering) {
  22830. this._rigCameras[1]._skipRendering = true;
  22831. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22832. }
  22833. }
  22834. break;
  22835. }
  22836. this._cascadePostProcessesToRigCams();
  22837. this.update();
  22838. };
  22839. Camera.prototype._getVRProjectionMatrix = function () {
  22840. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22841. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22842. return this._projectionMatrix;
  22843. };
  22844. Camera.prototype._updateCameraRotationMatrix = function () {
  22845. //Here for WebVR
  22846. };
  22847. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22848. //Here for WebVR
  22849. };
  22850. /**
  22851. * This function MUST be overwritten by the different WebVR cameras available.
  22852. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22853. */
  22854. Camera.prototype._getWebVRProjectionMatrix = function () {
  22855. return BABYLON.Matrix.Identity();
  22856. };
  22857. /**
  22858. * This function MUST be overwritten by the different WebVR cameras available.
  22859. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22860. */
  22861. Camera.prototype._getWebVRViewMatrix = function () {
  22862. return BABYLON.Matrix.Identity();
  22863. };
  22864. Camera.prototype.setCameraRigParameter = function (name, value) {
  22865. if (!this._cameraRigParams) {
  22866. this._cameraRigParams = {};
  22867. }
  22868. this._cameraRigParams[name] = value;
  22869. //provisionnally:
  22870. if (name === "interaxialDistance") {
  22871. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22872. }
  22873. };
  22874. /**
  22875. * needs to be overridden by children so sub has required properties to be copied
  22876. */
  22877. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22878. return null;
  22879. };
  22880. /**
  22881. * May need to be overridden by children
  22882. */
  22883. Camera.prototype._updateRigCameras = function () {
  22884. for (var i = 0; i < this._rigCameras.length; i++) {
  22885. this._rigCameras[i].minZ = this.minZ;
  22886. this._rigCameras[i].maxZ = this.maxZ;
  22887. this._rigCameras[i].fov = this.fov;
  22888. }
  22889. // only update viewport when ANAGLYPH
  22890. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22891. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22892. }
  22893. };
  22894. Camera.prototype._setupInputs = function () {
  22895. };
  22896. Camera.prototype.serialize = function () {
  22897. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22898. // Type
  22899. serializationObject.type = this.getClassName();
  22900. // Parent
  22901. if (this.parent) {
  22902. serializationObject.parentId = this.parent.id;
  22903. }
  22904. if (this.inputs) {
  22905. this.inputs.serialize(serializationObject);
  22906. }
  22907. // Animations
  22908. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22909. serializationObject.ranges = this.serializeAnimationRanges();
  22910. return serializationObject;
  22911. };
  22912. Camera.prototype.clone = function (name) {
  22913. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22914. };
  22915. Camera.prototype.getDirection = function (localAxis) {
  22916. var result = BABYLON.Vector3.Zero();
  22917. this.getDirectionToRef(localAxis, result);
  22918. return result;
  22919. };
  22920. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22921. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22922. };
  22923. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22924. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22925. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22926. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22927. interaxial_distance: interaxial_distance,
  22928. isStereoscopicSideBySide: isStereoscopicSideBySide
  22929. });
  22930. if (constructorFunc) {
  22931. return constructorFunc;
  22932. }
  22933. // Default to universal camera
  22934. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22935. };
  22936. Camera.prototype.computeWorldMatrix = function () {
  22937. return this.getWorldMatrix();
  22938. };
  22939. Camera.Parse = function (parsedCamera, scene) {
  22940. var type = parsedCamera.type;
  22941. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22942. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22943. // Parent
  22944. if (parsedCamera.parentId) {
  22945. camera._waitingParentId = parsedCamera.parentId;
  22946. }
  22947. //If camera has an input manager, let it parse inputs settings
  22948. if (camera.inputs) {
  22949. camera.inputs.parse(parsedCamera);
  22950. camera._setupInputs();
  22951. }
  22952. if (camera.setPosition) { // need to force position
  22953. camera.position.copyFromFloats(0, 0, 0);
  22954. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22955. }
  22956. // Target
  22957. if (parsedCamera.target) {
  22958. if (camera.setTarget) {
  22959. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22960. }
  22961. }
  22962. // Apply 3d rig, when found
  22963. if (parsedCamera.cameraRigMode) {
  22964. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22965. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22966. }
  22967. // Animations
  22968. if (parsedCamera.animations) {
  22969. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22970. var parsedAnimation = parsedCamera.animations[animationIndex];
  22971. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22972. }
  22973. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22974. }
  22975. if (parsedCamera.autoAnimate) {
  22976. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22977. }
  22978. return camera;
  22979. };
  22980. // Statics
  22981. Camera._PERSPECTIVE_CAMERA = 0;
  22982. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22983. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22984. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22985. Camera._RIG_MODE_NONE = 0;
  22986. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22987. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22988. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22989. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22990. Camera._RIG_MODE_VR = 20;
  22991. Camera._RIG_MODE_WEBVR = 21;
  22992. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22993. Camera.UseAlternateWebVRRendering = false;
  22994. __decorate([
  22995. BABYLON.serializeAsVector3()
  22996. ], Camera.prototype, "position", void 0);
  22997. __decorate([
  22998. BABYLON.serializeAsVector3()
  22999. ], Camera.prototype, "upVector", void 0);
  23000. __decorate([
  23001. BABYLON.serialize()
  23002. ], Camera.prototype, "orthoLeft", void 0);
  23003. __decorate([
  23004. BABYLON.serialize()
  23005. ], Camera.prototype, "orthoRight", void 0);
  23006. __decorate([
  23007. BABYLON.serialize()
  23008. ], Camera.prototype, "orthoBottom", void 0);
  23009. __decorate([
  23010. BABYLON.serialize()
  23011. ], Camera.prototype, "orthoTop", void 0);
  23012. __decorate([
  23013. BABYLON.serialize()
  23014. ], Camera.prototype, "fov", void 0);
  23015. __decorate([
  23016. BABYLON.serialize()
  23017. ], Camera.prototype, "minZ", void 0);
  23018. __decorate([
  23019. BABYLON.serialize()
  23020. ], Camera.prototype, "maxZ", void 0);
  23021. __decorate([
  23022. BABYLON.serialize()
  23023. ], Camera.prototype, "inertia", void 0);
  23024. __decorate([
  23025. BABYLON.serialize()
  23026. ], Camera.prototype, "mode", void 0);
  23027. __decorate([
  23028. BABYLON.serialize()
  23029. ], Camera.prototype, "layerMask", void 0);
  23030. __decorate([
  23031. BABYLON.serialize()
  23032. ], Camera.prototype, "fovMode", void 0);
  23033. __decorate([
  23034. BABYLON.serialize()
  23035. ], Camera.prototype, "cameraRigMode", void 0);
  23036. __decorate([
  23037. BABYLON.serialize()
  23038. ], Camera.prototype, "interaxialDistance", void 0);
  23039. __decorate([
  23040. BABYLON.serialize()
  23041. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23042. return Camera;
  23043. }(BABYLON.Node));
  23044. BABYLON.Camera = Camera;
  23045. })(BABYLON || (BABYLON = {}));
  23046. //# sourceMappingURL=babylon.camera.js.map
  23047. var BABYLON;
  23048. (function (BABYLON) {
  23049. var RenderingManager = /** @class */ (function () {
  23050. function RenderingManager(scene) {
  23051. this._renderingGroups = new Array();
  23052. this._autoClearDepthStencil = {};
  23053. this._customOpaqueSortCompareFn = {};
  23054. this._customAlphaTestSortCompareFn = {};
  23055. this._customTransparentSortCompareFn = {};
  23056. this._renderinGroupInfo = null;
  23057. this._scene = scene;
  23058. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23059. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23060. }
  23061. }
  23062. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23063. if (depth === void 0) { depth = true; }
  23064. if (stencil === void 0) { stencil = true; }
  23065. if (this._depthStencilBufferAlreadyCleaned) {
  23066. return;
  23067. }
  23068. this._scene.getEngine().clear(null, false, depth, stencil);
  23069. this._depthStencilBufferAlreadyCleaned = true;
  23070. };
  23071. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23072. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23073. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23074. var info = null;
  23075. if (observable) {
  23076. if (!this._renderinGroupInfo) {
  23077. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23078. }
  23079. info = this._renderinGroupInfo;
  23080. info.scene = this._scene;
  23081. info.camera = this._scene.activeCamera;
  23082. }
  23083. // Dispatch sprites
  23084. if (renderSprites) {
  23085. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23086. var manager = this._scene.spriteManagers[index];
  23087. this.dispatchSprites(manager);
  23088. }
  23089. }
  23090. // Render
  23091. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23092. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23093. var renderingGroup = this._renderingGroups[index];
  23094. if (!renderingGroup && !observable)
  23095. continue;
  23096. var renderingGroupMask = 0;
  23097. // Fire PRECLEAR stage
  23098. if (observable && info) {
  23099. renderingGroupMask = Math.pow(2, index);
  23100. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23101. info.renderingGroupId = index;
  23102. observable.notifyObservers(info, renderingGroupMask);
  23103. }
  23104. // Clear depth/stencil if needed
  23105. if (RenderingManager.AUTOCLEAR) {
  23106. var autoClear = this._autoClearDepthStencil[index];
  23107. if (autoClear && autoClear.autoClear) {
  23108. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23109. }
  23110. }
  23111. if (observable && info) {
  23112. // Fire PREOPAQUE stage
  23113. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23114. observable.notifyObservers(info, renderingGroupMask);
  23115. // Fire PRETRANSPARENT stage
  23116. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23117. observable.notifyObservers(info, renderingGroupMask);
  23118. }
  23119. if (renderingGroup) {
  23120. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23121. var step = _a[_i];
  23122. step.action(index);
  23123. }
  23124. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23125. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23126. var step = _c[_b];
  23127. step.action(index);
  23128. }
  23129. }
  23130. // Fire POSTTRANSPARENT stage
  23131. if (observable && info) {
  23132. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23133. observable.notifyObservers(info, renderingGroupMask);
  23134. }
  23135. }
  23136. };
  23137. RenderingManager.prototype.reset = function () {
  23138. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23139. var renderingGroup = this._renderingGroups[index];
  23140. if (renderingGroup) {
  23141. renderingGroup.prepare();
  23142. }
  23143. }
  23144. };
  23145. RenderingManager.prototype.dispose = function () {
  23146. this.freeRenderingGroups();
  23147. this._renderingGroups.length = 0;
  23148. };
  23149. /**
  23150. * Clear the info related to rendering groups preventing retention points during dispose.
  23151. */
  23152. RenderingManager.prototype.freeRenderingGroups = function () {
  23153. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23154. var renderingGroup = this._renderingGroups[index];
  23155. if (renderingGroup) {
  23156. renderingGroup.dispose();
  23157. }
  23158. }
  23159. };
  23160. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23161. if (this._renderingGroups[renderingGroupId] === undefined) {
  23162. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23163. }
  23164. };
  23165. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23166. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23167. this._prepareRenderingGroup(renderingGroupId);
  23168. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23169. };
  23170. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23171. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23172. this._prepareRenderingGroup(renderingGroupId);
  23173. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23174. };
  23175. /**
  23176. * @param subMesh The submesh to dispatch
  23177. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23178. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23179. */
  23180. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23181. if (mesh === undefined) {
  23182. mesh = subMesh.getMesh();
  23183. }
  23184. var renderingGroupId = mesh.renderingGroupId || 0;
  23185. this._prepareRenderingGroup(renderingGroupId);
  23186. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23187. };
  23188. /**
  23189. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23190. * This allowed control for front to back rendering or reversly depending of the special needs.
  23191. *
  23192. * @param renderingGroupId The rendering group id corresponding to its index
  23193. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23194. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23195. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23196. */
  23197. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23198. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23199. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23200. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23201. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23202. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23203. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23204. if (this._renderingGroups[renderingGroupId]) {
  23205. var group = this._renderingGroups[renderingGroupId];
  23206. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23207. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23208. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23209. }
  23210. };
  23211. /**
  23212. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23213. *
  23214. * @param renderingGroupId The rendering group id corresponding to its index
  23215. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23216. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23217. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23218. */
  23219. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23220. if (depth === void 0) { depth = true; }
  23221. if (stencil === void 0) { stencil = true; }
  23222. this._autoClearDepthStencil[renderingGroupId] = {
  23223. autoClear: autoClearDepthStencil,
  23224. depth: depth,
  23225. stencil: stencil
  23226. };
  23227. };
  23228. /**
  23229. * The max id used for rendering groups (not included)
  23230. */
  23231. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23232. /**
  23233. * The min id used for rendering groups (included)
  23234. */
  23235. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23236. /**
  23237. * Used to globally prevent autoclearing scenes.
  23238. */
  23239. RenderingManager.AUTOCLEAR = true;
  23240. return RenderingManager;
  23241. }());
  23242. BABYLON.RenderingManager = RenderingManager;
  23243. })(BABYLON || (BABYLON = {}));
  23244. //# sourceMappingURL=babylon.renderingManager.js.map
  23245. var BABYLON;
  23246. (function (BABYLON) {
  23247. var RenderingGroup = /** @class */ (function () {
  23248. /**
  23249. * Creates a new rendering group.
  23250. * @param index The rendering group index
  23251. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23252. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23253. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23254. */
  23255. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23256. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23257. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23258. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23259. this.index = index;
  23260. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23261. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23262. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23263. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23264. this._particleSystems = new BABYLON.SmartArray(256);
  23265. this._spriteManagers = new BABYLON.SmartArray(256);
  23266. this._edgesRenderers = new BABYLON.SmartArray(16);
  23267. this._scene = scene;
  23268. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23269. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23270. this.transparentSortCompareFn = transparentSortCompareFn;
  23271. }
  23272. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23273. /**
  23274. * Set the opaque sort comparison function.
  23275. * If null the sub meshes will be render in the order they were created
  23276. */
  23277. set: function (value) {
  23278. this._opaqueSortCompareFn = value;
  23279. if (value) {
  23280. this._renderOpaque = this.renderOpaqueSorted;
  23281. }
  23282. else {
  23283. this._renderOpaque = RenderingGroup.renderUnsorted;
  23284. }
  23285. },
  23286. enumerable: true,
  23287. configurable: true
  23288. });
  23289. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23290. /**
  23291. * Set the alpha test sort comparison function.
  23292. * If null the sub meshes will be render in the order they were created
  23293. */
  23294. set: function (value) {
  23295. this._alphaTestSortCompareFn = value;
  23296. if (value) {
  23297. this._renderAlphaTest = this.renderAlphaTestSorted;
  23298. }
  23299. else {
  23300. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23301. }
  23302. },
  23303. enumerable: true,
  23304. configurable: true
  23305. });
  23306. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23307. /**
  23308. * Set the transparent sort comparison function.
  23309. * If null the sub meshes will be render in the order they were created
  23310. */
  23311. set: function (value) {
  23312. if (value) {
  23313. this._transparentSortCompareFn = value;
  23314. }
  23315. else {
  23316. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23317. }
  23318. this._renderTransparent = this.renderTransparentSorted;
  23319. },
  23320. enumerable: true,
  23321. configurable: true
  23322. });
  23323. /**
  23324. * Render all the sub meshes contained in the group.
  23325. * @param customRenderFunction Used to override the default render behaviour of the group.
  23326. * @returns true if rendered some submeshes.
  23327. */
  23328. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23329. if (customRenderFunction) {
  23330. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23331. return;
  23332. }
  23333. var engine = this._scene.getEngine();
  23334. // Depth only
  23335. if (this._depthOnlySubMeshes.length !== 0) {
  23336. engine.setColorWrite(false);
  23337. this._renderAlphaTest(this._depthOnlySubMeshes);
  23338. engine.setColorWrite(true);
  23339. }
  23340. // Opaque
  23341. if (this._opaqueSubMeshes.length !== 0) {
  23342. this._renderOpaque(this._opaqueSubMeshes);
  23343. }
  23344. // Alpha test
  23345. if (this._alphaTestSubMeshes.length !== 0) {
  23346. this._renderAlphaTest(this._alphaTestSubMeshes);
  23347. }
  23348. var stencilState = engine.getStencilBuffer();
  23349. engine.setStencilBuffer(false);
  23350. // Sprites
  23351. if (renderSprites) {
  23352. this._renderSprites();
  23353. }
  23354. // Particles
  23355. if (renderParticles) {
  23356. this._renderParticles(activeMeshes);
  23357. }
  23358. if (this.onBeforeTransparentRendering) {
  23359. this.onBeforeTransparentRendering();
  23360. }
  23361. // Transparent
  23362. if (this._transparentSubMeshes.length !== 0) {
  23363. this._renderTransparent(this._transparentSubMeshes);
  23364. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23365. }
  23366. // Set back stencil to false in case it changes before the edge renderer.
  23367. engine.setStencilBuffer(false);
  23368. // Edges
  23369. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23370. this._edgesRenderers.data[edgesRendererIndex].render();
  23371. }
  23372. // Restore Stencil state.
  23373. engine.setStencilBuffer(stencilState);
  23374. };
  23375. /**
  23376. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23377. * @param subMeshes The submeshes to render
  23378. */
  23379. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23380. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23381. };
  23382. /**
  23383. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23384. * @param subMeshes The submeshes to render
  23385. */
  23386. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23387. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23388. };
  23389. /**
  23390. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23391. * @param subMeshes The submeshes to render
  23392. */
  23393. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23394. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23395. };
  23396. /**
  23397. * Renders the submeshes in a specified order.
  23398. * @param subMeshes The submeshes to sort before render
  23399. * @param sortCompareFn The comparison function use to sort
  23400. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23401. * @param transparent Specifies to activate blending if true
  23402. */
  23403. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23404. var subIndex = 0;
  23405. var subMesh;
  23406. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23407. for (; subIndex < subMeshes.length; subIndex++) {
  23408. subMesh = subMeshes.data[subIndex];
  23409. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23410. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23411. }
  23412. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23413. if (sortCompareFn) {
  23414. sortedArray.sort(sortCompareFn);
  23415. }
  23416. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23417. subMesh = sortedArray[subIndex];
  23418. if (transparent) {
  23419. var material = subMesh.getMaterial();
  23420. if (material && material.needDepthPrePass) {
  23421. var engine = material.getScene().getEngine();
  23422. engine.setColorWrite(false);
  23423. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23424. subMesh.render(false);
  23425. engine.setColorWrite(true);
  23426. }
  23427. }
  23428. subMesh.render(transparent);
  23429. }
  23430. };
  23431. /**
  23432. * Renders the submeshes in the order they were dispatched (no sort applied).
  23433. * @param subMeshes The submeshes to render
  23434. */
  23435. RenderingGroup.renderUnsorted = function (subMeshes) {
  23436. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23437. var submesh = subMeshes.data[subIndex];
  23438. submesh.render(false);
  23439. }
  23440. };
  23441. /**
  23442. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23443. * are rendered back to front if in the same alpha index.
  23444. *
  23445. * @param a The first submesh
  23446. * @param b The second submesh
  23447. * @returns The result of the comparison
  23448. */
  23449. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23450. // Alpha index first
  23451. if (a._alphaIndex > b._alphaIndex) {
  23452. return 1;
  23453. }
  23454. if (a._alphaIndex < b._alphaIndex) {
  23455. return -1;
  23456. }
  23457. // Then distance to camera
  23458. return RenderingGroup.backToFrontSortCompare(a, b);
  23459. };
  23460. /**
  23461. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23462. * are rendered back to front.
  23463. *
  23464. * @param a The first submesh
  23465. * @param b The second submesh
  23466. * @returns The result of the comparison
  23467. */
  23468. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23469. // Then distance to camera
  23470. if (a._distanceToCamera < b._distanceToCamera) {
  23471. return 1;
  23472. }
  23473. if (a._distanceToCamera > b._distanceToCamera) {
  23474. return -1;
  23475. }
  23476. return 0;
  23477. };
  23478. /**
  23479. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23480. * are rendered front to back (prevent overdraw).
  23481. *
  23482. * @param a The first submesh
  23483. * @param b The second submesh
  23484. * @returns The result of the comparison
  23485. */
  23486. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23487. // Then distance to camera
  23488. if (a._distanceToCamera < b._distanceToCamera) {
  23489. return -1;
  23490. }
  23491. if (a._distanceToCamera > b._distanceToCamera) {
  23492. return 1;
  23493. }
  23494. return 0;
  23495. };
  23496. /**
  23497. * Resets the different lists of submeshes to prepare a new frame.
  23498. */
  23499. RenderingGroup.prototype.prepare = function () {
  23500. this._opaqueSubMeshes.reset();
  23501. this._transparentSubMeshes.reset();
  23502. this._alphaTestSubMeshes.reset();
  23503. this._depthOnlySubMeshes.reset();
  23504. this._particleSystems.reset();
  23505. this._spriteManagers.reset();
  23506. this._edgesRenderers.reset();
  23507. };
  23508. RenderingGroup.prototype.dispose = function () {
  23509. this._opaqueSubMeshes.dispose();
  23510. this._transparentSubMeshes.dispose();
  23511. this._alphaTestSubMeshes.dispose();
  23512. this._depthOnlySubMeshes.dispose();
  23513. this._particleSystems.dispose();
  23514. this._spriteManagers.dispose();
  23515. this._edgesRenderers.dispose();
  23516. };
  23517. /**
  23518. * Inserts the submesh in its correct queue depending on its material.
  23519. * @param subMesh The submesh to dispatch
  23520. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23521. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23522. */
  23523. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23524. // Get mesh and materials if not provided
  23525. if (mesh === undefined) {
  23526. mesh = subMesh.getMesh();
  23527. }
  23528. if (material === undefined) {
  23529. material = subMesh.getMaterial();
  23530. }
  23531. if (material === null || material === undefined) {
  23532. return;
  23533. }
  23534. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23535. this._transparentSubMeshes.push(subMesh);
  23536. }
  23537. else if (material.needAlphaTesting()) { // Alpha test
  23538. if (material.needDepthPrePass) {
  23539. this._depthOnlySubMeshes.push(subMesh);
  23540. }
  23541. this._alphaTestSubMeshes.push(subMesh);
  23542. }
  23543. else {
  23544. if (material.needDepthPrePass) {
  23545. this._depthOnlySubMeshes.push(subMesh);
  23546. }
  23547. this._opaqueSubMeshes.push(subMesh); // Opaque
  23548. }
  23549. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23550. this._edgesRenderers.push(mesh._edgesRenderer);
  23551. }
  23552. };
  23553. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23554. this._spriteManagers.push(spriteManager);
  23555. };
  23556. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23557. this._particleSystems.push(particleSystem);
  23558. };
  23559. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23560. if (this._particleSystems.length === 0) {
  23561. return;
  23562. }
  23563. // Particles
  23564. var activeCamera = this._scene.activeCamera;
  23565. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23566. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23567. var particleSystem = this._particleSystems.data[particleIndex];
  23568. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23569. continue;
  23570. }
  23571. var emitter = particleSystem.emitter;
  23572. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23573. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23574. }
  23575. }
  23576. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23577. };
  23578. RenderingGroup.prototype._renderSprites = function () {
  23579. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23580. return;
  23581. }
  23582. // Sprites
  23583. var activeCamera = this._scene.activeCamera;
  23584. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23585. for (var id = 0; id < this._spriteManagers.length; id++) {
  23586. var spriteManager = this._spriteManagers.data[id];
  23587. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23588. spriteManager.render();
  23589. }
  23590. }
  23591. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23592. };
  23593. return RenderingGroup;
  23594. }());
  23595. BABYLON.RenderingGroup = RenderingGroup;
  23596. })(BABYLON || (BABYLON = {}));
  23597. //# sourceMappingURL=babylon.renderingGroup.js.map
  23598. var BABYLON;
  23599. (function (BABYLON) {
  23600. /**
  23601. * Groups all the scene component constants in one place to ease maintenance.
  23602. * @hidden
  23603. */
  23604. var SceneComponentConstants = /** @class */ (function () {
  23605. function SceneComponentConstants() {
  23606. }
  23607. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23608. SceneComponentConstants.NAME_LAYER = "Layer";
  23609. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23610. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23611. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23612. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23613. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23614. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23615. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23616. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23617. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23618. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23619. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23620. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23621. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 0;
  23622. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23623. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23624. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23625. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23626. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23627. return SceneComponentConstants;
  23628. }());
  23629. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23630. /**
  23631. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23632. * @hidden
  23633. */
  23634. var Stage = /** @class */ (function (_super) {
  23635. __extends(Stage, _super);
  23636. /**
  23637. * Hide ctor from the rest of the world.
  23638. * @param items The items to add.
  23639. */
  23640. function Stage(items) {
  23641. return _super.apply(this, items) || this;
  23642. }
  23643. /**
  23644. * Creates a new Stage.
  23645. * @returns A new instance of a Stage
  23646. */
  23647. Stage.Create = function () {
  23648. return Object.create(Stage.prototype);
  23649. };
  23650. /**
  23651. * Registers a step in an ordered way in the targeted stage.
  23652. * @param index Defines the position to register the step in
  23653. * @param component Defines the component attached to the step
  23654. * @param action Defines the action to launch during the step
  23655. */
  23656. Stage.prototype.registerStep = function (index, component, action) {
  23657. var i = 0;
  23658. var maxIndex = Number.MAX_VALUE;
  23659. for (; i < this.length && i < maxIndex; i++) {
  23660. var step = this[i];
  23661. maxIndex = step.index;
  23662. }
  23663. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23664. };
  23665. /**
  23666. * Clears all the steps from the stage.
  23667. */
  23668. Stage.prototype.clear = function () {
  23669. this.length = 0;
  23670. };
  23671. return Stage;
  23672. }(Array));
  23673. BABYLON.Stage = Stage;
  23674. })(BABYLON || (BABYLON = {}));
  23675. //# sourceMappingURL=babylon.sceneComponent.js.map
  23676. var BABYLON;
  23677. (function (BABYLON) {
  23678. /**
  23679. * Base class of the scene acting as a container for the different elements composing a scene.
  23680. * This class is dynamically extended by the different components of the scene increasing
  23681. * flexibility and reducing coupling
  23682. */
  23683. var AbstractScene = /** @class */ (function () {
  23684. function AbstractScene() {
  23685. /** All of the cameras added to this scene
  23686. * @see http://doc.babylonjs.com/babylon101/cameras
  23687. */
  23688. this.cameras = new Array();
  23689. /**
  23690. * All of the lights added to this scene
  23691. * @see http://doc.babylonjs.com/babylon101/lights
  23692. */
  23693. this.lights = new Array();
  23694. /**
  23695. * All of the (abstract) meshes added to this scene
  23696. */
  23697. this.meshes = new Array();
  23698. /**
  23699. * The list of skeletons added to the scene
  23700. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23701. */
  23702. this.skeletons = new Array();
  23703. /**
  23704. * All of the particle systems added to this scene
  23705. * @see http://doc.babylonjs.com/babylon101/particles
  23706. */
  23707. this.particleSystems = new Array();
  23708. /**
  23709. * Gets a list of Animations associated with the scene
  23710. */
  23711. this.animations = [];
  23712. /**
  23713. * All of the animation groups added to this scene
  23714. * @see http://doc.babylonjs.com/how_to/group
  23715. */
  23716. this.animationGroups = new Array();
  23717. /**
  23718. * All of the multi-materials added to this scene
  23719. * @see http://doc.babylonjs.com/how_to/multi_materials
  23720. */
  23721. this.multiMaterials = new Array();
  23722. /**
  23723. * All of the materials added to this scene
  23724. * @see http://doc.babylonjs.com/babylon101/materials
  23725. */
  23726. this.materials = new Array();
  23727. /**
  23728. * The list of morph target managers added to the scene
  23729. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23730. */
  23731. this.morphTargetManagers = new Array();
  23732. /**
  23733. * The list of geometries used in the scene.
  23734. */
  23735. this.geometries = new Array();
  23736. /**
  23737. * All of the tranform nodes added to this scene
  23738. * @see http://doc.babylonjs.com/how_to/transformnode
  23739. */
  23740. this.transformNodes = new Array();
  23741. /**
  23742. * ActionManagers available on the scene.
  23743. */
  23744. this.actionManagers = new Array();
  23745. /**
  23746. * Sounds to keep.
  23747. */
  23748. this.sounds = new Array();
  23749. /**
  23750. * Textures to keep.
  23751. */
  23752. this.textures = new Array();
  23753. }
  23754. /**
  23755. * Adds a parser in the list of available ones
  23756. * @param name Defines the name of the parser
  23757. * @param parser Defines the parser to add
  23758. */
  23759. AbstractScene.AddParser = function (name, parser) {
  23760. this._BabylonFileParsers[name] = parser;
  23761. };
  23762. /**
  23763. * Gets a general parser from the list of avaialble ones
  23764. * @param name Defines the name of the parser
  23765. * @returns the requested parser or null
  23766. */
  23767. AbstractScene.GetParser = function (name) {
  23768. if (this._BabylonFileParsers[name]) {
  23769. return this._BabylonFileParsers[name];
  23770. }
  23771. return null;
  23772. };
  23773. /**
  23774. * Adds n individual parser in the list of available ones
  23775. * @param name Defines the name of the parser
  23776. * @param parser Defines the parser to add
  23777. */
  23778. AbstractScene.AddIndividualParser = function (name, parser) {
  23779. this._IndividualBabylonFileParsers[name] = parser;
  23780. };
  23781. /**
  23782. * Gets an individual parser from the list of avaialble ones
  23783. * @param name Defines the name of the parser
  23784. * @returns the requested parser or null
  23785. */
  23786. AbstractScene.GetIndividualParser = function (name) {
  23787. if (this._IndividualBabylonFileParsers[name]) {
  23788. return this._IndividualBabylonFileParsers[name];
  23789. }
  23790. return null;
  23791. };
  23792. /**
  23793. * Parser json data and populate both a scene and its associated container object
  23794. * @param jsonData Defines the data to parse
  23795. * @param scene Defines the scene to parse the data for
  23796. * @param container Defines the container attached to the parsing sequence
  23797. * @param rootUrl Defines the root url of the data
  23798. */
  23799. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23800. for (var parserName in this._BabylonFileParsers) {
  23801. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23802. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23803. }
  23804. }
  23805. };
  23806. /**
  23807. * Stores the list of available parsers in the application.
  23808. */
  23809. AbstractScene._BabylonFileParsers = {};
  23810. /**
  23811. * Stores the list of available individual parsers in the application.
  23812. */
  23813. AbstractScene._IndividualBabylonFileParsers = {};
  23814. return AbstractScene;
  23815. }());
  23816. BABYLON.AbstractScene = AbstractScene;
  23817. })(BABYLON || (BABYLON = {}));
  23818. //# sourceMappingURL=babylon.abstractScene.js.map
  23819. var BABYLON;
  23820. (function (BABYLON) {
  23821. /** @hidden */
  23822. var ClickInfo = /** @class */ (function () {
  23823. function ClickInfo() {
  23824. this._singleClick = false;
  23825. this._doubleClick = false;
  23826. this._hasSwiped = false;
  23827. this._ignore = false;
  23828. }
  23829. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23830. get: function () {
  23831. return this._singleClick;
  23832. },
  23833. set: function (b) {
  23834. this._singleClick = b;
  23835. },
  23836. enumerable: true,
  23837. configurable: true
  23838. });
  23839. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23840. get: function () {
  23841. return this._doubleClick;
  23842. },
  23843. set: function (b) {
  23844. this._doubleClick = b;
  23845. },
  23846. enumerable: true,
  23847. configurable: true
  23848. });
  23849. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23850. get: function () {
  23851. return this._hasSwiped;
  23852. },
  23853. set: function (b) {
  23854. this._hasSwiped = b;
  23855. },
  23856. enumerable: true,
  23857. configurable: true
  23858. });
  23859. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23860. get: function () {
  23861. return this._ignore;
  23862. },
  23863. set: function (b) {
  23864. this._ignore = b;
  23865. },
  23866. enumerable: true,
  23867. configurable: true
  23868. });
  23869. return ClickInfo;
  23870. }());
  23871. /**
  23872. * This class is used by the onRenderingGroupObservable
  23873. */
  23874. var RenderingGroupInfo = /** @class */ (function () {
  23875. function RenderingGroupInfo() {
  23876. }
  23877. /**
  23878. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23879. * This stage will be fired no matter what
  23880. */
  23881. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23882. /**
  23883. * Called before opaque object are rendered.
  23884. * This stage will be fired only if there's 3D Opaque content to render
  23885. */
  23886. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23887. /**
  23888. * Called after the opaque objects are rendered and before the transparent ones
  23889. * This stage will be fired only if there's 3D transparent content to render
  23890. */
  23891. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23892. /**
  23893. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23894. * This stage will be fired no matter what
  23895. */
  23896. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23897. return RenderingGroupInfo;
  23898. }());
  23899. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23900. /**
  23901. * Represents a scene to be rendered by the engine.
  23902. * @see http://doc.babylonjs.com/features/scene
  23903. */
  23904. var Scene = /** @class */ (function (_super) {
  23905. __extends(Scene, _super);
  23906. /**
  23907. * Creates a new Scene
  23908. * @param engine defines the engine to use to render this scene
  23909. */
  23910. function Scene(engine) {
  23911. var _this = _super.call(this) || this;
  23912. // Members
  23913. /**
  23914. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23915. */
  23916. _this.autoClear = true;
  23917. /**
  23918. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23919. */
  23920. _this.autoClearDepthAndStencil = true;
  23921. /**
  23922. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23923. */
  23924. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23925. /**
  23926. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23927. */
  23928. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23929. _this._forceWireframe = false;
  23930. _this._forcePointsCloud = false;
  23931. /**
  23932. * Gets or sets a boolean indicating if animations are enabled
  23933. */
  23934. _this.animationsEnabled = true;
  23935. _this._animationPropertiesOverride = null;
  23936. /**
  23937. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23938. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23939. */
  23940. _this.useConstantAnimationDeltaTime = false;
  23941. /**
  23942. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23943. * Please note that it requires to run a ray cast through the scene on every frame
  23944. */
  23945. _this.constantlyUpdateMeshUnderPointer = false;
  23946. /**
  23947. * Defines the HTML cursor to use when hovering over interactive elements
  23948. */
  23949. _this.hoverCursor = "pointer";
  23950. /**
  23951. * Defines the HTML default cursor to use (empty by default)
  23952. */
  23953. _this.defaultCursor = "";
  23954. /**
  23955. * This is used to call preventDefault() on pointer down
  23956. * in order to block unwanted artifacts like system double clicks
  23957. */
  23958. _this.preventDefaultOnPointerDown = true;
  23959. // Metadata
  23960. /**
  23961. * Gets or sets user defined metadata
  23962. */
  23963. _this.metadata = null;
  23964. /**
  23965. * Use this array to add regular expressions used to disable offline support for specific urls
  23966. */
  23967. _this.disableOfflineSupportExceptionRules = new Array();
  23968. /**
  23969. * An event triggered when the scene is disposed.
  23970. */
  23971. _this.onDisposeObservable = new BABYLON.Observable();
  23972. _this._onDisposeObserver = null;
  23973. /**
  23974. * An event triggered before rendering the scene (right after animations and physics)
  23975. */
  23976. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23977. _this._onBeforeRenderObserver = null;
  23978. /**
  23979. * An event triggered after rendering the scene
  23980. */
  23981. _this.onAfterRenderObservable = new BABYLON.Observable();
  23982. _this._onAfterRenderObserver = null;
  23983. /**
  23984. * An event triggered before animating the scene
  23985. */
  23986. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23987. /**
  23988. * An event triggered after animations processing
  23989. */
  23990. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23991. /**
  23992. * An event triggered before draw calls are ready to be sent
  23993. */
  23994. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23995. /**
  23996. * An event triggered after draw calls have been sent
  23997. */
  23998. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23999. /**
  24000. * An event triggered when physic simulation is about to be run
  24001. */
  24002. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  24003. /**
  24004. * An event triggered when physic simulation has been done
  24005. */
  24006. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  24007. /**
  24008. * An event triggered when the scene is ready
  24009. */
  24010. _this.onReadyObservable = new BABYLON.Observable();
  24011. /**
  24012. * An event triggered before rendering a camera
  24013. */
  24014. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24015. _this._onBeforeCameraRenderObserver = null;
  24016. /**
  24017. * An event triggered after rendering a camera
  24018. */
  24019. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24020. _this._onAfterCameraRenderObserver = null;
  24021. /**
  24022. * An event triggered when active meshes evaluation is about to start
  24023. */
  24024. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24025. /**
  24026. * An event triggered when active meshes evaluation is done
  24027. */
  24028. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24029. /**
  24030. * An event triggered when particles rendering is about to start
  24031. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24032. */
  24033. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24034. /**
  24035. * An event triggered when particles rendering is done
  24036. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24037. */
  24038. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24039. /**
  24040. * An event triggered when sprites rendering is about to start
  24041. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24042. */
  24043. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24044. /**
  24045. * An event triggered when sprites rendering is done
  24046. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24047. */
  24048. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24049. /**
  24050. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24051. */
  24052. _this.onDataLoadedObservable = new BABYLON.Observable();
  24053. /**
  24054. * An event triggered when a camera is created
  24055. */
  24056. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24057. /**
  24058. * An event triggered when a camera is removed
  24059. */
  24060. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24061. /**
  24062. * An event triggered when a light is created
  24063. */
  24064. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24065. /**
  24066. * An event triggered when a light is removed
  24067. */
  24068. _this.onLightRemovedObservable = new BABYLON.Observable();
  24069. /**
  24070. * An event triggered when a geometry is created
  24071. */
  24072. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24073. /**
  24074. * An event triggered when a geometry is removed
  24075. */
  24076. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24077. /**
  24078. * An event triggered when a transform node is created
  24079. */
  24080. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24081. /**
  24082. * An event triggered when a transform node is removed
  24083. */
  24084. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24085. /**
  24086. * An event triggered when a mesh is created
  24087. */
  24088. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24089. /**
  24090. * An event triggered when a mesh is removed
  24091. */
  24092. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24093. /**
  24094. * An event triggered when render targets are about to be rendered
  24095. * Can happen multiple times per frame.
  24096. */
  24097. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24098. /**
  24099. * An event triggered when render targets were rendered.
  24100. * Can happen multiple times per frame.
  24101. */
  24102. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24103. /**
  24104. * An event triggered before calculating deterministic simulation step
  24105. */
  24106. _this.onBeforeStepObservable = new BABYLON.Observable();
  24107. /**
  24108. * An event triggered after calculating deterministic simulation step
  24109. */
  24110. _this.onAfterStepObservable = new BABYLON.Observable();
  24111. /**
  24112. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24113. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24114. * 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)
  24115. */
  24116. _this.onRenderingGroupObservable = new BABYLON.Observable();
  24117. // Animations
  24118. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24119. /**
  24120. * 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).
  24121. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24122. */
  24123. _this.onPrePointerObservable = new BABYLON.Observable();
  24124. /**
  24125. * Observable event triggered each time an input event is received from the rendering canvas
  24126. */
  24127. _this.onPointerObservable = new BABYLON.Observable();
  24128. _this._meshPickProceed = false;
  24129. _this._currentPickResult = null;
  24130. _this._previousPickResult = null;
  24131. _this._totalPointersPressed = 0;
  24132. _this._doubleClickOccured = false;
  24133. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24134. _this.cameraToUseForPointers = null;
  24135. _this._pointerX = 0;
  24136. _this._pointerY = 0;
  24137. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24138. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24139. _this._startingPointerTime = 0;
  24140. _this._previousStartingPointerTime = 0;
  24141. _this._pointerCaptures = {};
  24142. // Deterministic lockstep
  24143. _this._timeAccumulator = 0;
  24144. _this._currentStepId = 0;
  24145. _this._currentInternalStep = 0;
  24146. // Keyboard
  24147. /**
  24148. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24149. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24150. */
  24151. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24152. /**
  24153. * Observable event triggered each time an keyboard event is received from the hosting window
  24154. */
  24155. _this.onKeyboardObservable = new BABYLON.Observable();
  24156. // Coordinates system
  24157. _this._useRightHandedSystem = false;
  24158. // Fog
  24159. _this._fogEnabled = true;
  24160. _this._fogMode = Scene.FOGMODE_NONE;
  24161. /**
  24162. * Gets or sets the fog color to use
  24163. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24164. */
  24165. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24166. /**
  24167. * Gets or sets the fog density to use
  24168. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24169. */
  24170. _this.fogDensity = 0.1;
  24171. /**
  24172. * Gets or sets the fog start distance to use
  24173. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24174. */
  24175. _this.fogStart = 0;
  24176. /**
  24177. * Gets or sets the fog end distance to use
  24178. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24179. */
  24180. _this.fogEnd = 1000.0;
  24181. // Lights
  24182. _this._shadowsEnabled = true;
  24183. _this._lightsEnabled = true;
  24184. /** All of the active cameras added to this scene. */
  24185. _this.activeCameras = new Array();
  24186. // Textures
  24187. _this._texturesEnabled = true;
  24188. // Particles
  24189. /**
  24190. * Gets or sets a boolean indicating if particles are enabled on this scene
  24191. */
  24192. _this.particlesEnabled = true;
  24193. // Sprites
  24194. /**
  24195. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24196. */
  24197. _this.spritesEnabled = true;
  24198. /**
  24199. * All of the sprite managers added to this scene
  24200. * @see http://doc.babylonjs.com/babylon101/sprites
  24201. */
  24202. _this.spriteManagers = new Array();
  24203. // Skeletons
  24204. _this._skeletonsEnabled = true;
  24205. // Lens flares
  24206. /**
  24207. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24208. */
  24209. _this.lensFlaresEnabled = true;
  24210. // Collisions
  24211. /**
  24212. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24213. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24214. */
  24215. _this.collisionsEnabled = true;
  24216. /**
  24217. * Defines the gravity applied to this scene (used only for collisions)
  24218. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24219. */
  24220. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24221. // Postprocesses
  24222. /**
  24223. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24224. */
  24225. _this.postProcessesEnabled = true;
  24226. /**
  24227. * The list of postprocesses added to the scene
  24228. */
  24229. _this.postProcesses = new Array();
  24230. // Customs render targets
  24231. /**
  24232. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24233. */
  24234. _this.renderTargetsEnabled = true;
  24235. /**
  24236. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24237. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24238. */
  24239. _this.dumpNextRenderTargets = false;
  24240. /**
  24241. * The list of user defined render targets added to the scene
  24242. */
  24243. _this.customRenderTargets = new Array();
  24244. /**
  24245. * Gets the list of meshes imported to the scene through SceneLoader
  24246. */
  24247. _this.importedMeshesFiles = new Array();
  24248. // Probes
  24249. /**
  24250. * Gets or sets a boolean indicating if probes are enabled on this scene
  24251. */
  24252. _this.probesEnabled = true;
  24253. /**
  24254. * The list of reflection probes added to the scene
  24255. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24256. */
  24257. _this.reflectionProbes = new Array();
  24258. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24259. // Procedural textures
  24260. /**
  24261. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24262. */
  24263. _this.proceduralTexturesEnabled = true;
  24264. /**
  24265. * The list of procedural textures added to the scene
  24266. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24267. */
  24268. _this.proceduralTextures = new Array();
  24269. /**
  24270. * The list of sound tracks added to the scene
  24271. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24272. */
  24273. _this.soundTracks = new Array();
  24274. _this._audioEnabled = true;
  24275. _this._headphone = false;
  24276. // Performance counters
  24277. _this._totalVertices = new BABYLON.PerfCounter();
  24278. /** @hidden */
  24279. _this._activeIndices = new BABYLON.PerfCounter();
  24280. /** @hidden */
  24281. _this._activeParticles = new BABYLON.PerfCounter();
  24282. /** @hidden */
  24283. _this._activeBones = new BABYLON.PerfCounter();
  24284. _this._animationTime = 0;
  24285. /**
  24286. * Gets or sets a general scale for animation speed
  24287. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24288. */
  24289. _this.animationTimeScale = 1;
  24290. _this._renderId = 0;
  24291. _this._executeWhenReadyTimeoutId = -1;
  24292. _this._intermediateRendering = false;
  24293. _this._viewUpdateFlag = -1;
  24294. _this._projectionUpdateFlag = -1;
  24295. _this._alternateViewUpdateFlag = -1;
  24296. _this._alternateProjectionUpdateFlag = -1;
  24297. /** @hidden */
  24298. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24299. _this._activeRequests = new Array();
  24300. _this._pendingData = new Array();
  24301. _this._isDisposed = false;
  24302. /**
  24303. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24304. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24305. */
  24306. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24307. _this._activeMeshes = new BABYLON.SmartArray(256);
  24308. _this._processedMaterials = new BABYLON.SmartArray(256);
  24309. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24310. /** @hidden */
  24311. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24312. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24313. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24314. /** @hidden */
  24315. _this._activeAnimatables = new Array();
  24316. _this._transformMatrix = BABYLON.Matrix.Zero();
  24317. _this._useAlternateCameraConfiguration = false;
  24318. _this._alternateRendering = false;
  24319. /**
  24320. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24321. * This is useful if there are more lights that the maximum simulteanous authorized
  24322. */
  24323. _this.requireLightSorting = false;
  24324. _this._depthRenderer = {};
  24325. /**
  24326. * Backing store of defined scene components.
  24327. */
  24328. _this._components = [];
  24329. /**
  24330. * Backing store of defined scene components.
  24331. */
  24332. _this._serializableComponents = [];
  24333. /**
  24334. * List of components to register on the next registration step.
  24335. */
  24336. _this._transientComponents = [];
  24337. /**
  24338. * Defines the actions happening before camera updates.
  24339. */
  24340. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24341. /**
  24342. * Defines the actions happening during the per mesh ready checks.
  24343. */
  24344. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24345. /**
  24346. * Defines the actions happening before evaluate active mesh checks.
  24347. */
  24348. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24349. /**
  24350. * Defines the actions happening during the evaluate sub mesh checks.
  24351. */
  24352. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24353. /**
  24354. * Defines the actions happening during the active mesh stage.
  24355. */
  24356. _this._activeMeshStage = BABYLON.Stage.Create();
  24357. /**
  24358. * Defines the actions happening during the per camera render target step.
  24359. */
  24360. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24361. /**
  24362. * Defines the actions happening just before the active camera is drawing.
  24363. */
  24364. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24365. /**
  24366. * Defines the actions happening just before a rendering group is drawing.
  24367. */
  24368. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24369. /**
  24370. * Defines the actions happening just after a rendering group has been drawn.
  24371. */
  24372. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24373. /**
  24374. * Defines the actions happening just after the active camera has been drawn.
  24375. */
  24376. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24377. _this._activeMeshesFrozen = false;
  24378. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24379. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24380. _this._engine.scenes.push(_this);
  24381. _this._uid = null;
  24382. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24383. if (BABYLON.PostProcessManager) {
  24384. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24385. }
  24386. if (BABYLON.OutlineRenderer) {
  24387. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24388. }
  24389. if (BABYLON.Tools.IsWindowObjectExist()) {
  24390. _this.attachControl();
  24391. }
  24392. //simplification queue
  24393. if (BABYLON.SimplificationQueue) {
  24394. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24395. }
  24396. //collision coordinator initialization. For now legacy per default.
  24397. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24398. // Uniform Buffer
  24399. _this._createUbo();
  24400. // Default Image processing definition
  24401. if (BABYLON.ImageProcessingConfiguration) {
  24402. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24403. }
  24404. return _this;
  24405. }
  24406. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24407. /** The fog is deactivated */
  24408. get: function () {
  24409. return Scene._FOGMODE_NONE;
  24410. },
  24411. enumerable: true,
  24412. configurable: true
  24413. });
  24414. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24415. /** The fog density is following an exponential function */
  24416. get: function () {
  24417. return Scene._FOGMODE_EXP;
  24418. },
  24419. enumerable: true,
  24420. configurable: true
  24421. });
  24422. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24423. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24424. get: function () {
  24425. return Scene._FOGMODE_EXP2;
  24426. },
  24427. enumerable: true,
  24428. configurable: true
  24429. });
  24430. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24431. /** The fog density is following a linear function. */
  24432. get: function () {
  24433. return Scene._FOGMODE_LINEAR;
  24434. },
  24435. enumerable: true,
  24436. configurable: true
  24437. });
  24438. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24439. /**
  24440. * Texture used in all pbr material as the reflection texture.
  24441. * As in the majority of the scene they are the same (exception for multi room and so on),
  24442. * this is easier to reference from here than from all the materials.
  24443. */
  24444. get: function () {
  24445. return this._environmentTexture;
  24446. },
  24447. /**
  24448. * Texture used in all pbr material as the reflection texture.
  24449. * As in the majority of the scene they are the same (exception for multi room and so on),
  24450. * this is easier to set here than in all the materials.
  24451. */
  24452. set: function (value) {
  24453. if (this._environmentTexture === value) {
  24454. return;
  24455. }
  24456. this._environmentTexture = value;
  24457. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24458. },
  24459. enumerable: true,
  24460. configurable: true
  24461. });
  24462. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24463. /**
  24464. * Default image processing configuration used either in the rendering
  24465. * Forward main pass or through the imageProcessingPostProcess if present.
  24466. * As in the majority of the scene they are the same (exception for multi camera),
  24467. * this is easier to reference from here than from all the materials and post process.
  24468. *
  24469. * No setter as we it is a shared configuration, you can set the values instead.
  24470. */
  24471. get: function () {
  24472. return this._imageProcessingConfiguration;
  24473. },
  24474. enumerable: true,
  24475. configurable: true
  24476. });
  24477. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24478. get: function () {
  24479. return this._forceWireframe;
  24480. },
  24481. /**
  24482. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24483. */
  24484. set: function (value) {
  24485. if (this._forceWireframe === value) {
  24486. return;
  24487. }
  24488. this._forceWireframe = value;
  24489. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24490. },
  24491. enumerable: true,
  24492. configurable: true
  24493. });
  24494. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24495. get: function () {
  24496. return this._forcePointsCloud;
  24497. },
  24498. /**
  24499. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24500. */
  24501. set: function (value) {
  24502. if (this._forcePointsCloud === value) {
  24503. return;
  24504. }
  24505. this._forcePointsCloud = value;
  24506. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24507. },
  24508. enumerable: true,
  24509. configurable: true
  24510. });
  24511. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24512. /**
  24513. * Gets or sets the animation properties override
  24514. */
  24515. get: function () {
  24516. return this._animationPropertiesOverride;
  24517. },
  24518. set: function (value) {
  24519. this._animationPropertiesOverride = value;
  24520. },
  24521. enumerable: true,
  24522. configurable: true
  24523. });
  24524. Object.defineProperty(Scene.prototype, "onDispose", {
  24525. /** Sets a function to be executed when this scene is disposed. */
  24526. set: function (callback) {
  24527. if (this._onDisposeObserver) {
  24528. this.onDisposeObservable.remove(this._onDisposeObserver);
  24529. }
  24530. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24531. },
  24532. enumerable: true,
  24533. configurable: true
  24534. });
  24535. Object.defineProperty(Scene.prototype, "beforeRender", {
  24536. /** Sets a function to be executed before rendering this scene */
  24537. set: function (callback) {
  24538. if (this._onBeforeRenderObserver) {
  24539. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24540. }
  24541. if (callback) {
  24542. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24543. }
  24544. },
  24545. enumerable: true,
  24546. configurable: true
  24547. });
  24548. Object.defineProperty(Scene.prototype, "afterRender", {
  24549. /** Sets a function to be executed after rendering this scene */
  24550. set: function (callback) {
  24551. if (this._onAfterRenderObserver) {
  24552. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24553. }
  24554. if (callback) {
  24555. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24556. }
  24557. },
  24558. enumerable: true,
  24559. configurable: true
  24560. });
  24561. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24562. /** Sets a function to be executed before rendering a camera*/
  24563. set: function (callback) {
  24564. if (this._onBeforeCameraRenderObserver) {
  24565. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24566. }
  24567. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24568. },
  24569. enumerable: true,
  24570. configurable: true
  24571. });
  24572. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24573. /** Sets a function to be executed after rendering a camera*/
  24574. set: function (callback) {
  24575. if (this._onAfterCameraRenderObserver) {
  24576. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24577. }
  24578. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24579. },
  24580. enumerable: true,
  24581. configurable: true
  24582. });
  24583. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24584. /**
  24585. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24586. */
  24587. get: function () {
  24588. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24589. },
  24590. enumerable: true,
  24591. configurable: true
  24592. });
  24593. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24594. get: function () {
  24595. return this._useRightHandedSystem;
  24596. },
  24597. /**
  24598. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24599. */
  24600. set: function (value) {
  24601. if (this._useRightHandedSystem === value) {
  24602. return;
  24603. }
  24604. this._useRightHandedSystem = value;
  24605. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24606. },
  24607. enumerable: true,
  24608. configurable: true
  24609. });
  24610. /**
  24611. * Sets the step Id used by deterministic lock step
  24612. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24613. * @param newStepId defines the step Id
  24614. */
  24615. Scene.prototype.setStepId = function (newStepId) {
  24616. this._currentStepId = newStepId;
  24617. };
  24618. ;
  24619. /**
  24620. * Gets the step Id used by deterministic lock step
  24621. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24622. * @returns the step Id
  24623. */
  24624. Scene.prototype.getStepId = function () {
  24625. return this._currentStepId;
  24626. };
  24627. ;
  24628. /**
  24629. * Gets the internal step used by deterministic lock step
  24630. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24631. * @returns the internal step
  24632. */
  24633. Scene.prototype.getInternalStep = function () {
  24634. return this._currentInternalStep;
  24635. };
  24636. ;
  24637. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24638. get: function () {
  24639. return this._fogEnabled;
  24640. },
  24641. /**
  24642. * Gets or sets a boolean indicating if fog is enabled on this scene
  24643. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24644. */
  24645. set: function (value) {
  24646. if (this._fogEnabled === value) {
  24647. return;
  24648. }
  24649. this._fogEnabled = value;
  24650. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24651. },
  24652. enumerable: true,
  24653. configurable: true
  24654. });
  24655. Object.defineProperty(Scene.prototype, "fogMode", {
  24656. get: function () {
  24657. return this._fogMode;
  24658. },
  24659. /**
  24660. * Gets or sets the fog mode to use
  24661. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24662. */
  24663. set: function (value) {
  24664. if (this._fogMode === value) {
  24665. return;
  24666. }
  24667. this._fogMode = value;
  24668. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24669. },
  24670. enumerable: true,
  24671. configurable: true
  24672. });
  24673. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24674. get: function () {
  24675. return this._shadowsEnabled;
  24676. },
  24677. /**
  24678. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24679. */
  24680. set: function (value) {
  24681. if (this._shadowsEnabled === value) {
  24682. return;
  24683. }
  24684. this._shadowsEnabled = value;
  24685. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24686. },
  24687. enumerable: true,
  24688. configurable: true
  24689. });
  24690. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24691. get: function () {
  24692. return this._lightsEnabled;
  24693. },
  24694. /**
  24695. * Gets or sets a boolean indicating if lights are enabled on this scene
  24696. */
  24697. set: function (value) {
  24698. if (this._lightsEnabled === value) {
  24699. return;
  24700. }
  24701. this._lightsEnabled = value;
  24702. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24703. },
  24704. enumerable: true,
  24705. configurable: true
  24706. });
  24707. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24708. /** The default material used on meshes when no material is affected */
  24709. get: function () {
  24710. if (!this._defaultMaterial) {
  24711. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24712. }
  24713. return this._defaultMaterial;
  24714. },
  24715. /** The default material used on meshes when no material is affected */
  24716. set: function (value) {
  24717. this._defaultMaterial = value;
  24718. },
  24719. enumerable: true,
  24720. configurable: true
  24721. });
  24722. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24723. get: function () {
  24724. return this._texturesEnabled;
  24725. },
  24726. /**
  24727. * Gets or sets a boolean indicating if textures are enabled on this scene
  24728. */
  24729. set: function (value) {
  24730. if (this._texturesEnabled === value) {
  24731. return;
  24732. }
  24733. this._texturesEnabled = value;
  24734. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24735. },
  24736. enumerable: true,
  24737. configurable: true
  24738. });
  24739. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24740. get: function () {
  24741. return this._skeletonsEnabled;
  24742. },
  24743. /**
  24744. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24745. */
  24746. set: function (value) {
  24747. if (this._skeletonsEnabled === value) {
  24748. return;
  24749. }
  24750. this._skeletonsEnabled = value;
  24751. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24752. },
  24753. enumerable: true,
  24754. configurable: true
  24755. });
  24756. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24757. /**
  24758. * Gets the postprocess render pipeline manager
  24759. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24760. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24761. */
  24762. get: function () {
  24763. if (!this._postProcessRenderPipelineManager) {
  24764. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24765. }
  24766. return this._postProcessRenderPipelineManager;
  24767. },
  24768. enumerable: true,
  24769. configurable: true
  24770. });
  24771. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24772. /**
  24773. * Gets the main soundtrack associated with the scene
  24774. */
  24775. get: function () {
  24776. if (!this._mainSoundTrack) {
  24777. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24778. }
  24779. return this._mainSoundTrack;
  24780. },
  24781. enumerable: true,
  24782. configurable: true
  24783. });
  24784. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24785. /** @hidden */
  24786. get: function () {
  24787. return this._alternateRendering;
  24788. },
  24789. enumerable: true,
  24790. configurable: true
  24791. });
  24792. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24793. /**
  24794. * Gets the list of frustum planes (built from the active camera)
  24795. */
  24796. get: function () {
  24797. return this._frustumPlanes;
  24798. },
  24799. enumerable: true,
  24800. configurable: true
  24801. });
  24802. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24803. /**
  24804. * Gets the current geometry buffer associated to the scene.
  24805. */
  24806. get: function () {
  24807. return this._geometryBufferRenderer;
  24808. },
  24809. /**
  24810. * Sets the current geometry buffer for the scene.
  24811. */
  24812. set: function (geometryBufferRenderer) {
  24813. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24814. this._geometryBufferRenderer = geometryBufferRenderer;
  24815. }
  24816. },
  24817. enumerable: true,
  24818. configurable: true
  24819. });
  24820. /**
  24821. * Registers the transient components if needed.
  24822. */
  24823. Scene.prototype._registerTransientComponents = function () {
  24824. // Register components that have been associated lately to the scene.
  24825. if (this._transientComponents.length > 0) {
  24826. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24827. var component = _a[_i];
  24828. component.register();
  24829. }
  24830. this._transientComponents = [];
  24831. }
  24832. };
  24833. /**
  24834. * Add a component to the scene.
  24835. * Note that the ccomponent could be registered on th next frame if this is called after
  24836. * the register component stage.
  24837. * @param component Defines the component to add to the scene
  24838. */
  24839. Scene.prototype._addComponent = function (component) {
  24840. this._components.push(component);
  24841. this._transientComponents.push(component);
  24842. var serializableComponent = component;
  24843. if (serializableComponent.addFromContainer) {
  24844. this._serializableComponents.push(serializableComponent);
  24845. }
  24846. };
  24847. /**
  24848. * Gets a component from the scene.
  24849. * @param name defines the name of the component to retrieve
  24850. * @returns the component or null if not present
  24851. */
  24852. Scene.prototype._getComponent = function (name) {
  24853. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24854. var component = _a[_i];
  24855. if (component.name === name) {
  24856. return component;
  24857. }
  24858. }
  24859. return null;
  24860. };
  24861. Object.defineProperty(Scene.prototype, "debugLayer", {
  24862. /**
  24863. * Gets the debug layer (aka Inspector) associated with the scene
  24864. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24865. */
  24866. get: function () {
  24867. if (!this._debugLayer) {
  24868. this._debugLayer = new BABYLON.DebugLayer(this);
  24869. }
  24870. return this._debugLayer;
  24871. },
  24872. enumerable: true,
  24873. configurable: true
  24874. });
  24875. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24876. /**
  24877. * Gets a boolean indicating if collisions are processed on a web worker
  24878. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24879. */
  24880. get: function () {
  24881. return this._workerCollisions;
  24882. },
  24883. set: function (enabled) {
  24884. if (!BABYLON.CollisionCoordinatorLegacy) {
  24885. return;
  24886. }
  24887. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24888. this._workerCollisions = enabled;
  24889. if (this.collisionCoordinator) {
  24890. this.collisionCoordinator.destroy();
  24891. }
  24892. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24893. this.collisionCoordinator.init(this);
  24894. },
  24895. enumerable: true,
  24896. configurable: true
  24897. });
  24898. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24899. /**
  24900. * Gets the octree used to boost mesh selection (picking)
  24901. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24902. */
  24903. get: function () {
  24904. return this._selectionOctree;
  24905. },
  24906. enumerable: true,
  24907. configurable: true
  24908. });
  24909. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24910. /**
  24911. * Gets the mesh that is currently under the pointer
  24912. */
  24913. get: function () {
  24914. return this._pointerOverMesh;
  24915. },
  24916. enumerable: true,
  24917. configurable: true
  24918. });
  24919. Object.defineProperty(Scene.prototype, "pointerX", {
  24920. /**
  24921. * Gets the current on-screen X position of the pointer
  24922. */
  24923. get: function () {
  24924. return this._pointerX;
  24925. },
  24926. enumerable: true,
  24927. configurable: true
  24928. });
  24929. Object.defineProperty(Scene.prototype, "pointerY", {
  24930. /**
  24931. * Gets the current on-screen Y position of the pointer
  24932. */
  24933. get: function () {
  24934. return this._pointerY;
  24935. },
  24936. enumerable: true,
  24937. configurable: true
  24938. });
  24939. /**
  24940. * Gets the cached material (ie. the latest rendered one)
  24941. * @returns the cached material
  24942. */
  24943. Scene.prototype.getCachedMaterial = function () {
  24944. return this._cachedMaterial;
  24945. };
  24946. /**
  24947. * Gets the cached effect (ie. the latest rendered one)
  24948. * @returns the cached effect
  24949. */
  24950. Scene.prototype.getCachedEffect = function () {
  24951. return this._cachedEffect;
  24952. };
  24953. /**
  24954. * Gets the cached visibility state (ie. the latest rendered one)
  24955. * @returns the cached visibility state
  24956. */
  24957. Scene.prototype.getCachedVisibility = function () {
  24958. return this._cachedVisibility;
  24959. };
  24960. /**
  24961. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24962. * @param material defines the current material
  24963. * @param effect defines the current effect
  24964. * @param visibility defines the current visibility state
  24965. * @returns true if one parameter is not cached
  24966. */
  24967. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24968. if (visibility === void 0) { visibility = 1; }
  24969. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24970. };
  24971. /**
  24972. * Gets the outline renderer associated with the scene
  24973. * @returns a OutlineRenderer
  24974. */
  24975. Scene.prototype.getOutlineRenderer = function () {
  24976. return this._outlineRenderer;
  24977. };
  24978. /**
  24979. * Gets the engine associated with the scene
  24980. * @returns an Engine
  24981. */
  24982. Scene.prototype.getEngine = function () {
  24983. return this._engine;
  24984. };
  24985. /**
  24986. * Gets the total number of vertices rendered per frame
  24987. * @returns the total number of vertices rendered per frame
  24988. */
  24989. Scene.prototype.getTotalVertices = function () {
  24990. return this._totalVertices.current;
  24991. };
  24992. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24993. /**
  24994. * Gets the performance counter for total vertices
  24995. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24996. */
  24997. get: function () {
  24998. return this._totalVertices;
  24999. },
  25000. enumerable: true,
  25001. configurable: true
  25002. });
  25003. /**
  25004. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25005. * @returns the total number of active indices rendered per frame
  25006. */
  25007. Scene.prototype.getActiveIndices = function () {
  25008. return this._activeIndices.current;
  25009. };
  25010. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25011. /**
  25012. * Gets the performance counter for active indices
  25013. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25014. */
  25015. get: function () {
  25016. return this._activeIndices;
  25017. },
  25018. enumerable: true,
  25019. configurable: true
  25020. });
  25021. /**
  25022. * Gets the total number of active particles rendered per frame
  25023. * @returns the total number of active particles rendered per frame
  25024. */
  25025. Scene.prototype.getActiveParticles = function () {
  25026. return this._activeParticles.current;
  25027. };
  25028. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25029. /**
  25030. * Gets the performance counter for active particles
  25031. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25032. */
  25033. get: function () {
  25034. return this._activeParticles;
  25035. },
  25036. enumerable: true,
  25037. configurable: true
  25038. });
  25039. /**
  25040. * Gets the total number of active bones rendered per frame
  25041. * @returns the total number of active bones rendered per frame
  25042. */
  25043. Scene.prototype.getActiveBones = function () {
  25044. return this._activeBones.current;
  25045. };
  25046. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25047. /**
  25048. * Gets the performance counter for active bones
  25049. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25050. */
  25051. get: function () {
  25052. return this._activeBones;
  25053. },
  25054. enumerable: true,
  25055. configurable: true
  25056. });
  25057. /** @hidden */
  25058. Scene.prototype.getInterFramePerfCounter = function () {
  25059. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25060. return 0;
  25061. };
  25062. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25063. /** @hidden */
  25064. get: function () {
  25065. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25066. return null;
  25067. },
  25068. enumerable: true,
  25069. configurable: true
  25070. });
  25071. /** @hidden */
  25072. Scene.prototype.getLastFrameDuration = function () {
  25073. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25074. return 0;
  25075. };
  25076. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25077. /** @hidden */
  25078. get: function () {
  25079. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25080. return null;
  25081. },
  25082. enumerable: true,
  25083. configurable: true
  25084. });
  25085. /** @hidden */
  25086. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25087. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25088. return 0;
  25089. };
  25090. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25091. /** @hidden */
  25092. get: function () {
  25093. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25094. return null;
  25095. },
  25096. enumerable: true,
  25097. configurable: true
  25098. });
  25099. /**
  25100. * Gets the array of active meshes
  25101. * @returns an array of AbstractMesh
  25102. */
  25103. Scene.prototype.getActiveMeshes = function () {
  25104. return this._activeMeshes;
  25105. };
  25106. /** @hidden */
  25107. Scene.prototype.getRenderTargetsDuration = function () {
  25108. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25109. return 0;
  25110. };
  25111. /** @hidden */
  25112. Scene.prototype.getRenderDuration = function () {
  25113. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25114. return 0;
  25115. };
  25116. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25117. /** @hidden */
  25118. get: function () {
  25119. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25120. return null;
  25121. },
  25122. enumerable: true,
  25123. configurable: true
  25124. });
  25125. /** @hidden */
  25126. Scene.prototype.getParticlesDuration = function () {
  25127. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25128. return 0;
  25129. };
  25130. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25131. /** @hidden */
  25132. get: function () {
  25133. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25134. return null;
  25135. },
  25136. enumerable: true,
  25137. configurable: true
  25138. });
  25139. /** @hidden */
  25140. Scene.prototype.getSpritesDuration = function () {
  25141. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25142. return 0;
  25143. };
  25144. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25145. /** @hidden */
  25146. get: function () {
  25147. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25148. return null;
  25149. },
  25150. enumerable: true,
  25151. configurable: true
  25152. });
  25153. /**
  25154. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25155. * @returns a number
  25156. */
  25157. Scene.prototype.getAnimationRatio = function () {
  25158. return this._animationRatio;
  25159. };
  25160. /**
  25161. * Gets an unique Id for the current frame
  25162. * @returns a number
  25163. */
  25164. Scene.prototype.getRenderId = function () {
  25165. return this._renderId;
  25166. };
  25167. /** Call this function if you want to manually increment the render Id*/
  25168. Scene.prototype.incrementRenderId = function () {
  25169. this._renderId++;
  25170. };
  25171. Scene.prototype._updatePointerPosition = function (evt) {
  25172. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25173. if (!canvasRect) {
  25174. return;
  25175. }
  25176. this._pointerX = evt.clientX - canvasRect.left;
  25177. this._pointerY = evt.clientY - canvasRect.top;
  25178. this._unTranslatedPointerX = this._pointerX;
  25179. this._unTranslatedPointerY = this._pointerY;
  25180. };
  25181. Scene.prototype._createUbo = function () {
  25182. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25183. this._sceneUbo.addUniform("viewProjection", 16);
  25184. this._sceneUbo.addUniform("view", 16);
  25185. };
  25186. Scene.prototype._createAlternateUbo = function () {
  25187. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25188. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25189. this._alternateSceneUbo.addUniform("view", 16);
  25190. };
  25191. // Pointers handling
  25192. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25193. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25194. if (result) {
  25195. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25196. }
  25197. return result;
  25198. };
  25199. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25200. if (pointerInfo.pickInfo) {
  25201. if (!pointerInfo.pickInfo.ray) {
  25202. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25203. }
  25204. }
  25205. };
  25206. /**
  25207. * Use this method to simulate a pointer move on a mesh
  25208. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25209. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25210. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25211. * @returns the current scene
  25212. */
  25213. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25214. var evt = new PointerEvent("pointermove", pointerEventInit);
  25215. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25216. return this;
  25217. }
  25218. return this._processPointerMove(pickResult, evt);
  25219. };
  25220. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25221. var canvas = this._engine.getRenderingCanvas();
  25222. if (!canvas) {
  25223. return this;
  25224. }
  25225. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25226. this.setPointerOverSprite(null);
  25227. this.setPointerOverMesh(pickResult.pickedMesh);
  25228. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25229. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25230. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25231. }
  25232. else {
  25233. canvas.style.cursor = this.hoverCursor;
  25234. }
  25235. }
  25236. else {
  25237. canvas.style.cursor = this.defaultCursor;
  25238. }
  25239. }
  25240. else {
  25241. this.setPointerOverMesh(null);
  25242. // Sprites
  25243. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25244. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25245. this.setPointerOverSprite(pickResult.pickedSprite);
  25246. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25247. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25248. }
  25249. else {
  25250. canvas.style.cursor = this.hoverCursor;
  25251. }
  25252. }
  25253. else {
  25254. this.setPointerOverSprite(null);
  25255. // Restore pointer
  25256. canvas.style.cursor = this.defaultCursor;
  25257. }
  25258. }
  25259. if (pickResult) {
  25260. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25261. if (this.onPointerMove) {
  25262. this.onPointerMove(evt, pickResult, type);
  25263. }
  25264. if (this.onPointerObservable.hasObservers()) {
  25265. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25266. this._setRayOnPointerInfo(pi);
  25267. this.onPointerObservable.notifyObservers(pi, type);
  25268. }
  25269. }
  25270. return this;
  25271. };
  25272. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25273. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25274. if (pickResult) {
  25275. pi.ray = pickResult.ray;
  25276. }
  25277. this.onPrePointerObservable.notifyObservers(pi, type);
  25278. if (pi.skipOnPointerObservable) {
  25279. return true;
  25280. }
  25281. else {
  25282. return false;
  25283. }
  25284. };
  25285. /**
  25286. * Use this method to simulate a pointer down on a mesh
  25287. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25288. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25289. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25290. * @returns the current scene
  25291. */
  25292. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25293. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25294. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25295. return this;
  25296. }
  25297. return this._processPointerDown(pickResult, evt);
  25298. };
  25299. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25300. var _this = this;
  25301. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25302. this._pickedDownMesh = pickResult.pickedMesh;
  25303. var actionManager = pickResult.pickedMesh.actionManager;
  25304. if (actionManager) {
  25305. if (actionManager.hasPickTriggers) {
  25306. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25307. switch (evt.button) {
  25308. case 0:
  25309. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25310. break;
  25311. case 1:
  25312. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25313. break;
  25314. case 2:
  25315. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25316. break;
  25317. }
  25318. }
  25319. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25320. window.setTimeout(function () {
  25321. 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);
  25322. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25323. if (_this._totalPointersPressed !== 0 &&
  25324. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25325. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25326. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25327. _this._startingPointerTime = 0;
  25328. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25329. }
  25330. }
  25331. }, Scene.LongPressDelay);
  25332. }
  25333. }
  25334. }
  25335. if (pickResult) {
  25336. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25337. if (this.onPointerDown) {
  25338. this.onPointerDown(evt, pickResult, type);
  25339. }
  25340. if (this.onPointerObservable.hasObservers()) {
  25341. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25342. this._setRayOnPointerInfo(pi);
  25343. this.onPointerObservable.notifyObservers(pi, type);
  25344. }
  25345. }
  25346. return this;
  25347. };
  25348. /**
  25349. * Use this method to simulate a pointer up on a mesh
  25350. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25351. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25352. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25353. * @returns the current scene
  25354. */
  25355. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25356. var evt = new PointerEvent("pointerup", pointerEventInit);
  25357. var clickInfo = new ClickInfo();
  25358. clickInfo.singleClick = true;
  25359. clickInfo.ignore = true;
  25360. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25361. return this;
  25362. }
  25363. return this._processPointerUp(pickResult, evt, clickInfo);
  25364. };
  25365. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25366. if (pickResult && pickResult && pickResult.pickedMesh) {
  25367. this._pickedUpMesh = pickResult.pickedMesh;
  25368. if (this._pickedDownMesh === this._pickedUpMesh) {
  25369. if (this.onPointerPick) {
  25370. this.onPointerPick(evt, pickResult);
  25371. }
  25372. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25373. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25374. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25375. this._setRayOnPointerInfo(pi);
  25376. this.onPointerObservable.notifyObservers(pi, type_1);
  25377. }
  25378. }
  25379. if (pickResult.pickedMesh.actionManager) {
  25380. if (clickInfo.ignore) {
  25381. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25382. }
  25383. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25384. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25385. }
  25386. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25387. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25388. }
  25389. }
  25390. }
  25391. if (this._pickedDownMesh &&
  25392. this._pickedDownMesh.actionManager &&
  25393. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25394. this._pickedDownMesh !== this._pickedUpMesh) {
  25395. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25396. }
  25397. var type = BABYLON.PointerEventTypes.POINTERUP;
  25398. if (this.onPointerObservable.hasObservers()) {
  25399. if (!clickInfo.ignore) {
  25400. if (!clickInfo.hasSwiped) {
  25401. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25402. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25403. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25404. this._setRayOnPointerInfo(pi);
  25405. this.onPointerObservable.notifyObservers(pi, type_2);
  25406. }
  25407. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25408. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25409. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25410. this._setRayOnPointerInfo(pi);
  25411. this.onPointerObservable.notifyObservers(pi, type_3);
  25412. }
  25413. }
  25414. }
  25415. else {
  25416. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25417. this._setRayOnPointerInfo(pi);
  25418. this.onPointerObservable.notifyObservers(pi, type);
  25419. }
  25420. }
  25421. if (this.onPointerUp) {
  25422. this.onPointerUp(evt, pickResult, type);
  25423. }
  25424. return this;
  25425. };
  25426. /**
  25427. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25428. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25429. * @returns true if the pointer was captured
  25430. */
  25431. Scene.prototype.isPointerCaptured = function (pointerId) {
  25432. if (pointerId === void 0) { pointerId = 0; }
  25433. return this._pointerCaptures[pointerId];
  25434. };
  25435. /**
  25436. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25437. * @param attachUp defines if you want to attach events to pointerup
  25438. * @param attachDown defines if you want to attach events to pointerdown
  25439. * @param attachMove defines if you want to attach events to pointermove
  25440. */
  25441. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25442. var _this = this;
  25443. if (attachUp === void 0) { attachUp = true; }
  25444. if (attachDown === void 0) { attachDown = true; }
  25445. if (attachMove === void 0) { attachMove = true; }
  25446. this._initActionManager = function (act, clickInfo) {
  25447. if (!_this._meshPickProceed) {
  25448. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25449. _this._currentPickResult = pickResult;
  25450. if (pickResult) {
  25451. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25452. }
  25453. _this._meshPickProceed = true;
  25454. }
  25455. return act;
  25456. };
  25457. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25458. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25459. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25460. btn !== _this._previousButtonPressed) {
  25461. _this._doubleClickOccured = false;
  25462. clickInfo.singleClick = true;
  25463. clickInfo.ignore = false;
  25464. cb(clickInfo, _this._currentPickResult);
  25465. }
  25466. };
  25467. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25468. var clickInfo = new ClickInfo();
  25469. _this._currentPickResult = null;
  25470. var act = null;
  25471. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25472. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25473. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25474. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25475. act = _this._initActionManager(act, clickInfo);
  25476. if (act)
  25477. checkPicking = act.hasPickTriggers;
  25478. }
  25479. if (checkPicking) {
  25480. var btn = evt.button;
  25481. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25482. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25483. if (!clickInfo.hasSwiped) {
  25484. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25485. if (!checkSingleClickImmediately) {
  25486. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25487. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25488. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25489. act = _this._initActionManager(act, clickInfo);
  25490. if (act)
  25491. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25492. }
  25493. }
  25494. if (checkSingleClickImmediately) {
  25495. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25496. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25497. btn !== _this._previousButtonPressed) {
  25498. clickInfo.singleClick = true;
  25499. cb(clickInfo, _this._currentPickResult);
  25500. }
  25501. }
  25502. // at least one double click is required to be check and exclusive double click is enabled
  25503. else {
  25504. // wait that no double click has been raised during the double click delay
  25505. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25506. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25507. }
  25508. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25509. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25510. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25511. act = _this._initActionManager(act, clickInfo);
  25512. if (act)
  25513. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25514. }
  25515. if (checkDoubleClick) {
  25516. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25517. if (btn === _this._previousButtonPressed &&
  25518. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25519. !_this._doubleClickOccured) {
  25520. // pointer has not moved for 2 clicks, it's a double click
  25521. if (!clickInfo.hasSwiped &&
  25522. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25523. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25524. _this._previousStartingPointerTime = 0;
  25525. _this._doubleClickOccured = true;
  25526. clickInfo.doubleClick = true;
  25527. clickInfo.ignore = false;
  25528. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25529. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25530. }
  25531. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25532. cb(clickInfo, _this._currentPickResult);
  25533. }
  25534. // if the two successive clicks are too far, it's just two simple clicks
  25535. else {
  25536. _this._doubleClickOccured = false;
  25537. _this._previousStartingPointerTime = _this._startingPointerTime;
  25538. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25539. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25540. _this._previousButtonPressed = btn;
  25541. if (Scene.ExclusiveDoubleClickMode) {
  25542. if (_this._previousDelayedSimpleClickTimeout) {
  25543. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25544. }
  25545. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25546. cb(clickInfo, _this._previousPickResult);
  25547. }
  25548. else {
  25549. cb(clickInfo, _this._currentPickResult);
  25550. }
  25551. }
  25552. }
  25553. // just the first click of the double has been raised
  25554. else {
  25555. _this._doubleClickOccured = false;
  25556. _this._previousStartingPointerTime = _this._startingPointerTime;
  25557. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25558. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25559. _this._previousButtonPressed = btn;
  25560. }
  25561. }
  25562. }
  25563. }
  25564. clickInfo.ignore = true;
  25565. cb(clickInfo, _this._currentPickResult);
  25566. };
  25567. this._spritePredicate = function (sprite) {
  25568. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25569. };
  25570. this._onPointerMove = function (evt) {
  25571. _this._updatePointerPosition(evt);
  25572. // PreObservable support
  25573. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25574. return;
  25575. }
  25576. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25577. return;
  25578. }
  25579. if (!_this.pointerMovePredicate) {
  25580. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25581. }
  25582. // Meshes
  25583. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25584. _this._processPointerMove(pickResult, evt);
  25585. };
  25586. this._onPointerDown = function (evt) {
  25587. _this._totalPointersPressed++;
  25588. _this._pickedDownMesh = null;
  25589. _this._meshPickProceed = false;
  25590. _this._updatePointerPosition(evt);
  25591. if (_this.preventDefaultOnPointerDown && canvas) {
  25592. evt.preventDefault();
  25593. canvas.focus();
  25594. }
  25595. // PreObservable support
  25596. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25597. return;
  25598. }
  25599. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25600. return;
  25601. }
  25602. _this._pointerCaptures[evt.pointerId] = true;
  25603. _this._startingPointerPosition.x = _this._pointerX;
  25604. _this._startingPointerPosition.y = _this._pointerY;
  25605. _this._startingPointerTime = Date.now();
  25606. if (!_this.pointerDownPredicate) {
  25607. _this.pointerDownPredicate = function (mesh) {
  25608. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25609. };
  25610. }
  25611. // Meshes
  25612. _this._pickedDownMesh = null;
  25613. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25614. _this._processPointerDown(pickResult, evt);
  25615. // Sprites
  25616. _this._pickedDownSprite = null;
  25617. if (_this.spriteManagers.length > 0) {
  25618. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25619. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25620. if (pickResult.pickedSprite.actionManager) {
  25621. _this._pickedDownSprite = pickResult.pickedSprite;
  25622. switch (evt.button) {
  25623. case 0:
  25624. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25625. break;
  25626. case 1:
  25627. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25628. break;
  25629. case 2:
  25630. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25631. break;
  25632. }
  25633. if (pickResult.pickedSprite.actionManager) {
  25634. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25635. }
  25636. }
  25637. }
  25638. }
  25639. };
  25640. this._onPointerUp = function (evt) {
  25641. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25642. return; // So we need to test it the pointer down was pressed before.
  25643. }
  25644. _this._totalPointersPressed--;
  25645. _this._pickedUpMesh = null;
  25646. _this._meshPickProceed = false;
  25647. _this._updatePointerPosition(evt);
  25648. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25649. // PreObservable support
  25650. if (_this.onPrePointerObservable.hasObservers()) {
  25651. if (!clickInfo.ignore) {
  25652. if (!clickInfo.hasSwiped) {
  25653. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25654. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25655. return;
  25656. }
  25657. }
  25658. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25659. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25660. return;
  25661. }
  25662. }
  25663. }
  25664. }
  25665. else {
  25666. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25667. return;
  25668. }
  25669. }
  25670. }
  25671. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25672. return;
  25673. }
  25674. _this._pointerCaptures[evt.pointerId] = false;
  25675. if (!_this.pointerUpPredicate) {
  25676. _this.pointerUpPredicate = function (mesh) {
  25677. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25678. };
  25679. }
  25680. // Meshes
  25681. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25682. _this._initActionManager(null, clickInfo);
  25683. }
  25684. if (!pickResult) {
  25685. pickResult = _this._currentPickResult;
  25686. }
  25687. _this._processPointerUp(pickResult, evt, clickInfo);
  25688. // Sprites
  25689. if (!clickInfo.ignore) {
  25690. if (_this.spriteManagers.length > 0) {
  25691. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25692. if (spritePickResult) {
  25693. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25694. if (spritePickResult.pickedSprite.actionManager) {
  25695. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25696. if (spritePickResult.pickedSprite.actionManager) {
  25697. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25698. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25699. }
  25700. }
  25701. }
  25702. }
  25703. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25704. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25705. }
  25706. }
  25707. }
  25708. }
  25709. _this._previousPickResult = _this._currentPickResult;
  25710. });
  25711. };
  25712. this._onKeyDown = function (evt) {
  25713. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25714. if (_this.onPreKeyboardObservable.hasObservers()) {
  25715. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25716. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25717. if (pi.skipOnPointerObservable) {
  25718. return;
  25719. }
  25720. }
  25721. if (_this.onKeyboardObservable.hasObservers()) {
  25722. var pi = new BABYLON.KeyboardInfo(type, evt);
  25723. _this.onKeyboardObservable.notifyObservers(pi, type);
  25724. }
  25725. if (_this.actionManager) {
  25726. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25727. }
  25728. };
  25729. this._onKeyUp = function (evt) {
  25730. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25731. if (_this.onPreKeyboardObservable.hasObservers()) {
  25732. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25733. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25734. if (pi.skipOnPointerObservable) {
  25735. return;
  25736. }
  25737. }
  25738. if (_this.onKeyboardObservable.hasObservers()) {
  25739. var pi = new BABYLON.KeyboardInfo(type, evt);
  25740. _this.onKeyboardObservable.notifyObservers(pi, type);
  25741. }
  25742. if (_this.actionManager) {
  25743. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25744. }
  25745. };
  25746. var engine = this.getEngine();
  25747. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25748. if (!canvas) {
  25749. return;
  25750. }
  25751. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25752. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25753. });
  25754. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25755. if (!canvas) {
  25756. return;
  25757. }
  25758. canvas.removeEventListener("keydown", _this._onKeyDown);
  25759. canvas.removeEventListener("keyup", _this._onKeyUp);
  25760. });
  25761. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25762. var canvas = this._engine.getRenderingCanvas();
  25763. if (!canvas) {
  25764. return;
  25765. }
  25766. if (attachMove) {
  25767. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25768. // Wheel
  25769. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25770. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25771. }
  25772. if (attachDown) {
  25773. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25774. }
  25775. if (attachUp) {
  25776. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25777. }
  25778. canvas.tabIndex = 1;
  25779. };
  25780. /** Detaches all event handlers*/
  25781. Scene.prototype.detachControl = function () {
  25782. var engine = this.getEngine();
  25783. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25784. var canvas = engine.getRenderingCanvas();
  25785. if (!canvas) {
  25786. return;
  25787. }
  25788. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25789. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25790. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25791. if (this._onCanvasBlurObserver) {
  25792. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25793. }
  25794. if (this._onCanvasFocusObserver) {
  25795. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25796. }
  25797. // Wheel
  25798. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25799. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25800. // Keyboard
  25801. canvas.removeEventListener("keydown", this._onKeyDown);
  25802. canvas.removeEventListener("keyup", this._onKeyUp);
  25803. // Observables
  25804. this.onKeyboardObservable.clear();
  25805. this.onPreKeyboardObservable.clear();
  25806. this.onPointerObservable.clear();
  25807. this.onPrePointerObservable.clear();
  25808. };
  25809. /**
  25810. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25811. * Delay loaded resources are not taking in account
  25812. * @return true if all required resources are ready
  25813. */
  25814. Scene.prototype.isReady = function () {
  25815. if (this._isDisposed) {
  25816. return false;
  25817. }
  25818. if (this._pendingData.length > 0) {
  25819. return false;
  25820. }
  25821. var index;
  25822. var engine = this.getEngine();
  25823. // Geometries
  25824. for (index = 0; index < this.geometries.length; index++) {
  25825. var geometry = this.geometries[index];
  25826. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25827. return false;
  25828. }
  25829. }
  25830. // Meshes
  25831. for (index = 0; index < this.meshes.length; index++) {
  25832. var mesh = this.meshes[index];
  25833. if (!mesh.isEnabled()) {
  25834. continue;
  25835. }
  25836. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25837. continue;
  25838. }
  25839. if (!mesh.isReady(true)) {
  25840. return false;
  25841. }
  25842. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25843. // Is Ready For Mesh
  25844. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25845. var step = _a[_i];
  25846. if (!step.action(mesh, hardwareInstancedRendering)) {
  25847. return false;
  25848. }
  25849. }
  25850. }
  25851. // Post-processes
  25852. if (this.activeCameras && this.activeCameras.length > 0) {
  25853. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25854. var camera = _c[_b];
  25855. if (!camera.isReady(true)) {
  25856. return false;
  25857. }
  25858. }
  25859. }
  25860. else if (this.activeCamera) {
  25861. if (!this.activeCamera.isReady(true)) {
  25862. return false;
  25863. }
  25864. }
  25865. // Particles
  25866. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25867. var particleSystem = _e[_d];
  25868. if (!particleSystem.isReady()) {
  25869. return false;
  25870. }
  25871. }
  25872. return true;
  25873. };
  25874. /** Resets all cached information relative to material (including effect and visibility) */
  25875. Scene.prototype.resetCachedMaterial = function () {
  25876. this._cachedMaterial = null;
  25877. this._cachedEffect = null;
  25878. this._cachedVisibility = null;
  25879. };
  25880. /**
  25881. * Registers a function to be called before every frame render
  25882. * @param func defines the function to register
  25883. */
  25884. Scene.prototype.registerBeforeRender = function (func) {
  25885. this.onBeforeRenderObservable.add(func);
  25886. };
  25887. /**
  25888. * Unregisters a function called before every frame render
  25889. * @param func defines the function to unregister
  25890. */
  25891. Scene.prototype.unregisterBeforeRender = function (func) {
  25892. this.onBeforeRenderObservable.removeCallback(func);
  25893. };
  25894. /**
  25895. * Registers a function to be called after every frame render
  25896. * @param func defines the function to register
  25897. */
  25898. Scene.prototype.registerAfterRender = function (func) {
  25899. this.onAfterRenderObservable.add(func);
  25900. };
  25901. /**
  25902. * Unregisters a function called after every frame render
  25903. * @param func defines the function to unregister
  25904. */
  25905. Scene.prototype.unregisterAfterRender = function (func) {
  25906. this.onAfterRenderObservable.removeCallback(func);
  25907. };
  25908. Scene.prototype._executeOnceBeforeRender = function (func) {
  25909. var _this = this;
  25910. var execFunc = function () {
  25911. func();
  25912. setTimeout(function () {
  25913. _this.unregisterBeforeRender(execFunc);
  25914. });
  25915. };
  25916. this.registerBeforeRender(execFunc);
  25917. };
  25918. /**
  25919. * The provided function will run before render once and will be disposed afterwards.
  25920. * A timeout delay can be provided so that the function will be executed in N ms.
  25921. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25922. * @param func The function to be executed.
  25923. * @param timeout optional delay in ms
  25924. */
  25925. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25926. var _this = this;
  25927. if (timeout !== undefined) {
  25928. setTimeout(function () {
  25929. _this._executeOnceBeforeRender(func);
  25930. }, timeout);
  25931. }
  25932. else {
  25933. this._executeOnceBeforeRender(func);
  25934. }
  25935. };
  25936. /** @hidden */
  25937. Scene.prototype._addPendingData = function (data) {
  25938. this._pendingData.push(data);
  25939. };
  25940. /** @hidden */
  25941. Scene.prototype._removePendingData = function (data) {
  25942. var wasLoading = this.isLoading;
  25943. var index = this._pendingData.indexOf(data);
  25944. if (index !== -1) {
  25945. this._pendingData.splice(index, 1);
  25946. }
  25947. if (wasLoading && !this.isLoading) {
  25948. this.onDataLoadedObservable.notifyObservers(this);
  25949. }
  25950. };
  25951. /**
  25952. * Returns the number of items waiting to be loaded
  25953. * @returns the number of items waiting to be loaded
  25954. */
  25955. Scene.prototype.getWaitingItemsCount = function () {
  25956. return this._pendingData.length;
  25957. };
  25958. Object.defineProperty(Scene.prototype, "isLoading", {
  25959. /**
  25960. * Returns a boolean indicating if the scene is still loading data
  25961. */
  25962. get: function () {
  25963. return this._pendingData.length > 0;
  25964. },
  25965. enumerable: true,
  25966. configurable: true
  25967. });
  25968. /**
  25969. * Registers a function to be executed when the scene is ready
  25970. * @param {Function} func - the function to be executed
  25971. */
  25972. Scene.prototype.executeWhenReady = function (func) {
  25973. var _this = this;
  25974. this.onReadyObservable.add(func);
  25975. if (this._executeWhenReadyTimeoutId !== -1) {
  25976. return;
  25977. }
  25978. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25979. _this._checkIsReady();
  25980. }, 150);
  25981. };
  25982. /**
  25983. * Returns a promise that resolves when the scene is ready
  25984. * @returns A promise that resolves when the scene is ready
  25985. */
  25986. Scene.prototype.whenReadyAsync = function () {
  25987. var _this = this;
  25988. return new Promise(function (resolve) {
  25989. _this.executeWhenReady(function () {
  25990. resolve();
  25991. });
  25992. });
  25993. };
  25994. /** @hidden */
  25995. Scene.prototype._checkIsReady = function () {
  25996. var _this = this;
  25997. this._registerTransientComponents();
  25998. if (this.isReady()) {
  25999. this.onReadyObservable.notifyObservers(this);
  26000. this.onReadyObservable.clear();
  26001. this._executeWhenReadyTimeoutId = -1;
  26002. return;
  26003. }
  26004. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26005. _this._checkIsReady();
  26006. }, 150);
  26007. };
  26008. // Animations
  26009. /**
  26010. * Will start the animation sequence of a given target
  26011. * @param target defines the target
  26012. * @param from defines from which frame should animation start
  26013. * @param to defines until which frame should animation run.
  26014. * @param weight defines the weight to apply to the animation (1.0 by default)
  26015. * @param loop defines if the animation loops
  26016. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26017. * @param onAnimationEnd defines the function to be executed when the animation ends
  26018. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26019. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26020. * @returns the animatable object created for this animation
  26021. */
  26022. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26023. if (weight === void 0) { weight = 1.0; }
  26024. if (speedRatio === void 0) { speedRatio = 1.0; }
  26025. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26026. returnedAnimatable.weight = weight;
  26027. return returnedAnimatable;
  26028. };
  26029. /**
  26030. * Will start the animation sequence of a given target
  26031. * @param target defines the target
  26032. * @param from defines from which frame should animation start
  26033. * @param to defines until which frame should animation run.
  26034. * @param loop defines if the animation loops
  26035. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26036. * @param onAnimationEnd defines the function to be executed when the animation ends
  26037. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26038. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26039. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26040. * @returns the animatable object created for this animation
  26041. */
  26042. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26043. if (speedRatio === void 0) { speedRatio = 1.0; }
  26044. if (stopCurrent === void 0) { stopCurrent = true; }
  26045. if (from > to && speedRatio > 0) {
  26046. speedRatio *= -1;
  26047. }
  26048. if (stopCurrent) {
  26049. this.stopAnimation(target, undefined, targetMask);
  26050. }
  26051. if (!animatable) {
  26052. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26053. }
  26054. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26055. // Local animations
  26056. if (target.animations && shouldRunTargetAnimations) {
  26057. animatable.appendAnimations(target, target.animations);
  26058. }
  26059. // Children animations
  26060. if (target.getAnimatables) {
  26061. var animatables = target.getAnimatables();
  26062. for (var index = 0; index < animatables.length; index++) {
  26063. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26064. }
  26065. }
  26066. animatable.reset();
  26067. return animatable;
  26068. };
  26069. /**
  26070. * Begin a new animation on a given node
  26071. * @param target defines the target where the animation will take place
  26072. * @param animations defines the list of animations to start
  26073. * @param from defines the initial value
  26074. * @param to defines the final value
  26075. * @param loop defines if you want animation to loop (off by default)
  26076. * @param speedRatio defines the speed ratio to apply to all animations
  26077. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26078. * @returns the list of created animatables
  26079. */
  26080. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26081. if (speedRatio === undefined) {
  26082. speedRatio = 1.0;
  26083. }
  26084. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26085. return animatable;
  26086. };
  26087. /**
  26088. * Begin a new animation on a given node and its hierarchy
  26089. * @param target defines the root node where the animation will take place
  26090. * @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.
  26091. * @param animations defines the list of animations to start
  26092. * @param from defines the initial value
  26093. * @param to defines the final value
  26094. * @param loop defines if you want animation to loop (off by default)
  26095. * @param speedRatio defines the speed ratio to apply to all animations
  26096. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26097. * @returns the list of animatables created for all nodes
  26098. */
  26099. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26100. var children = target.getDescendants(directDescendantsOnly);
  26101. var result = [];
  26102. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26103. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26104. var child = children_1[_i];
  26105. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26106. }
  26107. return result;
  26108. };
  26109. /**
  26110. * Gets the animatable associated with a specific target
  26111. * @param target defines the target of the animatable
  26112. * @returns the required animatable if found
  26113. */
  26114. Scene.prototype.getAnimatableByTarget = function (target) {
  26115. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26116. if (this._activeAnimatables[index].target === target) {
  26117. return this._activeAnimatables[index];
  26118. }
  26119. }
  26120. return null;
  26121. };
  26122. /**
  26123. * Gets all animatables associated with a given target
  26124. * @param target defines the target to look animatables for
  26125. * @returns an array of Animatables
  26126. */
  26127. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26128. var result = [];
  26129. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26130. if (this._activeAnimatables[index].target === target) {
  26131. result.push(this._activeAnimatables[index]);
  26132. }
  26133. }
  26134. return result;
  26135. };
  26136. Object.defineProperty(Scene.prototype, "animatables", {
  26137. /**
  26138. * Gets all animatable attached to the scene
  26139. */
  26140. get: function () {
  26141. return this._activeAnimatables;
  26142. },
  26143. enumerable: true,
  26144. configurable: true
  26145. });
  26146. /**
  26147. * Will stop the animation of the given target
  26148. * @param target - the target
  26149. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26150. * @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)
  26151. */
  26152. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26153. var animatables = this.getAllAnimatablesByTarget(target);
  26154. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26155. var animatable = animatables_1[_i];
  26156. animatable.stop(animationName, targetMask);
  26157. }
  26158. };
  26159. /**
  26160. * Stops and removes all animations that have been applied to the scene
  26161. */
  26162. Scene.prototype.stopAllAnimations = function () {
  26163. if (this._activeAnimatables) {
  26164. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26165. this._activeAnimatables[i].stop();
  26166. }
  26167. this._activeAnimatables = [];
  26168. }
  26169. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26170. var group = _a[_i];
  26171. group.stop();
  26172. }
  26173. };
  26174. Scene.prototype._animate = function () {
  26175. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26176. return;
  26177. }
  26178. // Getting time
  26179. var now = BABYLON.Tools.Now;
  26180. if (!this._animationTimeLast) {
  26181. if (this._pendingData.length > 0) {
  26182. return;
  26183. }
  26184. this._animationTimeLast = now;
  26185. }
  26186. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26187. this._animationTime += deltaTime;
  26188. this._animationTimeLast = now;
  26189. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26190. this._activeAnimatables[index]._animate(this._animationTime);
  26191. }
  26192. // Late animation bindings
  26193. this._processLateAnimationBindings();
  26194. };
  26195. /** @hidden */
  26196. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26197. var target = runtimeAnimation.target;
  26198. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26199. if (!target._lateAnimationHolders) {
  26200. target._lateAnimationHolders = {};
  26201. }
  26202. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26203. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26204. totalWeight: 0,
  26205. animations: [],
  26206. originalValue: originalValue
  26207. };
  26208. }
  26209. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26210. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26211. };
  26212. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26213. var normalizer = 1.0;
  26214. var finalPosition = BABYLON.Tmp.Vector3[0];
  26215. var finalScaling = BABYLON.Tmp.Vector3[1];
  26216. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26217. var startIndex = 0;
  26218. var originalAnimation = holder.animations[0];
  26219. var originalValue = holder.originalValue;
  26220. var scale = 1;
  26221. if (holder.totalWeight < 1.0) {
  26222. // We need to mix the original value in
  26223. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26224. scale = 1.0 - holder.totalWeight;
  26225. }
  26226. else {
  26227. startIndex = 1;
  26228. // We need to normalize the weights
  26229. normalizer = holder.totalWeight;
  26230. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26231. scale = originalAnimation.weight / normalizer;
  26232. if (scale == 1) {
  26233. return originalAnimation.currentValue;
  26234. }
  26235. }
  26236. finalScaling.scaleInPlace(scale);
  26237. finalPosition.scaleInPlace(scale);
  26238. finalQuaternion.scaleInPlace(scale);
  26239. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26240. var runtimeAnimation = holder.animations[animIndex];
  26241. var scale = runtimeAnimation.weight / normalizer;
  26242. var currentPosition = BABYLON.Tmp.Vector3[2];
  26243. var currentScaling = BABYLON.Tmp.Vector3[3];
  26244. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26245. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26246. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26247. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26248. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26249. }
  26250. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26251. return originalAnimation._workValue;
  26252. };
  26253. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26254. var originalAnimation = holder.animations[0];
  26255. var originalValue = holder.originalValue;
  26256. if (holder.animations.length === 1) {
  26257. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26258. }
  26259. var normalizer = 1.0;
  26260. var quaternions;
  26261. var weights;
  26262. if (holder.totalWeight < 1.0) {
  26263. var scale = 1.0 - holder.totalWeight;
  26264. quaternions = [];
  26265. weights = [];
  26266. quaternions.push(originalValue);
  26267. weights.push(scale);
  26268. }
  26269. else {
  26270. if (holder.animations.length === 2) { // Slerp as soon as we can
  26271. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26272. }
  26273. quaternions = [];
  26274. weights = [];
  26275. normalizer = holder.totalWeight;
  26276. }
  26277. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26278. var runtimeAnimation = holder.animations[animIndex];
  26279. quaternions.push(runtimeAnimation.currentValue);
  26280. weights.push(runtimeAnimation.weight / normalizer);
  26281. }
  26282. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26283. var cumulativeAmount = 0;
  26284. var cumulativeQuaternion = null;
  26285. for (var index = 0; index < quaternions.length;) {
  26286. if (!cumulativeQuaternion) {
  26287. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26288. cumulativeAmount = weights[index] + weights[index + 1];
  26289. index += 2;
  26290. continue;
  26291. }
  26292. cumulativeAmount += weights[index];
  26293. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26294. index++;
  26295. }
  26296. return cumulativeQuaternion;
  26297. };
  26298. Scene.prototype._processLateAnimationBindings = function () {
  26299. if (!this._registeredForLateAnimationBindings.length) {
  26300. return;
  26301. }
  26302. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26303. var target = this._registeredForLateAnimationBindings.data[index];
  26304. for (var path in target._lateAnimationHolders) {
  26305. var holder = target._lateAnimationHolders[path];
  26306. var originalAnimation = holder.animations[0];
  26307. var originalValue = holder.originalValue;
  26308. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26309. var finalValue = void 0;
  26310. if (matrixDecomposeMode) {
  26311. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26312. }
  26313. else {
  26314. var quaternionMode = originalValue.w !== undefined;
  26315. if (quaternionMode) {
  26316. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26317. }
  26318. else {
  26319. var startIndex = 0;
  26320. var normalizer = 1.0;
  26321. if (holder.totalWeight < 1.0) {
  26322. // We need to mix the original value in
  26323. if (originalValue.scale) {
  26324. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26325. }
  26326. else {
  26327. finalValue = originalValue * (1.0 - holder.totalWeight);
  26328. }
  26329. }
  26330. else {
  26331. // We need to normalize the weights
  26332. normalizer = holder.totalWeight;
  26333. var scale_1 = originalAnimation.weight / normalizer;
  26334. if (scale_1 !== 1) {
  26335. if (originalAnimation.currentValue.scale) {
  26336. finalValue = originalAnimation.currentValue.scale(scale_1);
  26337. }
  26338. else {
  26339. finalValue = originalAnimation.currentValue * scale_1;
  26340. }
  26341. }
  26342. else {
  26343. finalValue = originalAnimation.currentValue;
  26344. }
  26345. startIndex = 1;
  26346. }
  26347. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26348. var runtimeAnimation = holder.animations[animIndex];
  26349. var scale = runtimeAnimation.weight / normalizer;
  26350. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26351. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26352. }
  26353. else {
  26354. finalValue += runtimeAnimation.currentValue * scale;
  26355. }
  26356. }
  26357. }
  26358. }
  26359. target[path] = finalValue;
  26360. }
  26361. target._lateAnimationHolders = {};
  26362. }
  26363. this._registeredForLateAnimationBindings.reset();
  26364. };
  26365. // Matrix
  26366. /** @hidden */
  26367. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26368. this._useAlternateCameraConfiguration = active;
  26369. };
  26370. /**
  26371. * Gets the current view matrix
  26372. * @returns a Matrix
  26373. */
  26374. Scene.prototype.getViewMatrix = function () {
  26375. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26376. };
  26377. /**
  26378. * Gets the current projection matrix
  26379. * @returns a Matrix
  26380. */
  26381. Scene.prototype.getProjectionMatrix = function () {
  26382. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26383. };
  26384. /**
  26385. * Gets the current transform matrix
  26386. * @returns a Matrix made of View * Projection
  26387. */
  26388. Scene.prototype.getTransformMatrix = function () {
  26389. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26390. };
  26391. /**
  26392. * Sets the current transform matrix
  26393. * @param view defines the View matrix to use
  26394. * @param projection defines the Projection matrix to use
  26395. */
  26396. Scene.prototype.setTransformMatrix = function (view, projection) {
  26397. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26398. return;
  26399. }
  26400. this._viewUpdateFlag = view.updateFlag;
  26401. this._projectionUpdateFlag = projection.updateFlag;
  26402. this._viewMatrix = view;
  26403. this._projectionMatrix = projection;
  26404. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26405. // Update frustum
  26406. if (!this._frustumPlanes) {
  26407. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26408. }
  26409. else {
  26410. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26411. }
  26412. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26413. var otherCamera = this.activeCamera._alternateCamera;
  26414. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26415. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26416. }
  26417. if (this._sceneUbo.useUbo) {
  26418. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26419. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26420. this._sceneUbo.update();
  26421. }
  26422. };
  26423. /** @hidden */
  26424. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26425. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26426. return;
  26427. }
  26428. this._alternateViewUpdateFlag = view.updateFlag;
  26429. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26430. this._alternateViewMatrix = view;
  26431. this._alternateProjectionMatrix = projection;
  26432. if (!this._alternateTransformMatrix) {
  26433. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26434. }
  26435. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26436. if (!this._alternateSceneUbo) {
  26437. this._createAlternateUbo();
  26438. }
  26439. if (this._alternateSceneUbo.useUbo) {
  26440. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26441. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26442. this._alternateSceneUbo.update();
  26443. }
  26444. };
  26445. /**
  26446. * Gets the uniform buffer used to store scene data
  26447. * @returns a UniformBuffer
  26448. */
  26449. Scene.prototype.getSceneUniformBuffer = function () {
  26450. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26451. };
  26452. /**
  26453. * Gets an unique (relatively to the current scene) Id
  26454. * @returns an unique number for the scene
  26455. */
  26456. Scene.prototype.getUniqueId = function () {
  26457. var result = Scene._uniqueIdCounter;
  26458. Scene._uniqueIdCounter++;
  26459. return result;
  26460. };
  26461. /**
  26462. * Add a mesh to the list of scene's meshes
  26463. * @param newMesh defines the mesh to add
  26464. * @param recursive if all child meshes should also be added to the scene
  26465. */
  26466. Scene.prototype.addMesh = function (newMesh, recursive) {
  26467. var _this = this;
  26468. if (recursive === void 0) { recursive = false; }
  26469. this.meshes.push(newMesh);
  26470. //notify the collision coordinator
  26471. if (this.collisionCoordinator) {
  26472. this.collisionCoordinator.onMeshAdded(newMesh);
  26473. }
  26474. newMesh._resyncLightSources();
  26475. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26476. if (recursive) {
  26477. newMesh.getChildMeshes().forEach(function (m) {
  26478. _this.addMesh(m);
  26479. });
  26480. }
  26481. };
  26482. /**
  26483. * Remove a mesh for the list of scene's meshes
  26484. * @param toRemove defines the mesh to remove
  26485. * @param recursive if all child meshes should also be removed from the scene
  26486. * @returns the index where the mesh was in the mesh list
  26487. */
  26488. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26489. var _this = this;
  26490. if (recursive === void 0) { recursive = false; }
  26491. var index = this.meshes.indexOf(toRemove);
  26492. if (index !== -1) {
  26493. // Remove from the scene if mesh found
  26494. this.meshes.splice(index, 1);
  26495. }
  26496. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26497. if (recursive) {
  26498. toRemove.getChildMeshes().forEach(function (m) {
  26499. _this.removeMesh(m);
  26500. });
  26501. }
  26502. return index;
  26503. };
  26504. /**
  26505. * Add a transform node to the list of scene's transform nodes
  26506. * @param newTransformNode defines the transform node to add
  26507. */
  26508. Scene.prototype.addTransformNode = function (newTransformNode) {
  26509. this.transformNodes.push(newTransformNode);
  26510. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26511. };
  26512. /**
  26513. * Remove a transform node for the list of scene's transform nodes
  26514. * @param toRemove defines the transform node to remove
  26515. * @returns the index where the transform node was in the transform node list
  26516. */
  26517. Scene.prototype.removeTransformNode = function (toRemove) {
  26518. var index = this.transformNodes.indexOf(toRemove);
  26519. if (index !== -1) {
  26520. // Remove from the scene if found
  26521. this.transformNodes.splice(index, 1);
  26522. }
  26523. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26524. return index;
  26525. };
  26526. /**
  26527. * Remove a skeleton for the list of scene's skeletons
  26528. * @param toRemove defines the skeleton to remove
  26529. * @returns the index where the skeleton was in the skeleton list
  26530. */
  26531. Scene.prototype.removeSkeleton = function (toRemove) {
  26532. var index = this.skeletons.indexOf(toRemove);
  26533. if (index !== -1) {
  26534. // Remove from the scene if found
  26535. this.skeletons.splice(index, 1);
  26536. }
  26537. return index;
  26538. };
  26539. /**
  26540. * Remove a morph target for the list of scene's morph targets
  26541. * @param toRemove defines the morph target to remove
  26542. * @returns the index where the morph target was in the morph target list
  26543. */
  26544. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26545. var index = this.morphTargetManagers.indexOf(toRemove);
  26546. if (index !== -1) {
  26547. // Remove from the scene if found
  26548. this.morphTargetManagers.splice(index, 1);
  26549. }
  26550. return index;
  26551. };
  26552. /**
  26553. * Remove a light for the list of scene's lights
  26554. * @param toRemove defines the light to remove
  26555. * @returns the index where the light was in the light list
  26556. */
  26557. Scene.prototype.removeLight = function (toRemove) {
  26558. var index = this.lights.indexOf(toRemove);
  26559. if (index !== -1) {
  26560. // Remove from meshes
  26561. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26562. var mesh = _a[_i];
  26563. mesh._removeLightSource(toRemove);
  26564. }
  26565. // Remove from the scene if mesh found
  26566. this.lights.splice(index, 1);
  26567. this.sortLightsByPriority();
  26568. }
  26569. this.onLightRemovedObservable.notifyObservers(toRemove);
  26570. return index;
  26571. };
  26572. /**
  26573. * Remove a camera for the list of scene's cameras
  26574. * @param toRemove defines the camera to remove
  26575. * @returns the index where the camera was in the camera list
  26576. */
  26577. Scene.prototype.removeCamera = function (toRemove) {
  26578. var index = this.cameras.indexOf(toRemove);
  26579. if (index !== -1) {
  26580. // Remove from the scene if mesh found
  26581. this.cameras.splice(index, 1);
  26582. }
  26583. // Remove from activeCameras
  26584. var index2 = this.activeCameras.indexOf(toRemove);
  26585. if (index2 !== -1) {
  26586. // Remove from the scene if mesh found
  26587. this.activeCameras.splice(index2, 1);
  26588. }
  26589. // Reset the activeCamera
  26590. if (this.activeCamera === toRemove) {
  26591. if (this.cameras.length > 0) {
  26592. this.activeCamera = this.cameras[0];
  26593. }
  26594. else {
  26595. this.activeCamera = null;
  26596. }
  26597. }
  26598. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26599. return index;
  26600. };
  26601. /**
  26602. * Remove a particle system for the list of scene's particle systems
  26603. * @param toRemove defines the particle system to remove
  26604. * @returns the index where the particle system was in the particle system list
  26605. */
  26606. Scene.prototype.removeParticleSystem = function (toRemove) {
  26607. var index = this.particleSystems.indexOf(toRemove);
  26608. if (index !== -1) {
  26609. this.particleSystems.splice(index, 1);
  26610. }
  26611. return index;
  26612. };
  26613. /**
  26614. * Remove a animation for the list of scene's animations
  26615. * @param toRemove defines the animation to remove
  26616. * @returns the index where the animation was in the animation list
  26617. */
  26618. Scene.prototype.removeAnimation = function (toRemove) {
  26619. var index = this.animations.indexOf(toRemove);
  26620. if (index !== -1) {
  26621. this.animations.splice(index, 1);
  26622. }
  26623. return index;
  26624. };
  26625. /**
  26626. * Removes the given animation group from this scene.
  26627. * @param toRemove The animation group to remove
  26628. * @returns The index of the removed animation group
  26629. */
  26630. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26631. var index = this.animationGroups.indexOf(toRemove);
  26632. if (index !== -1) {
  26633. this.animationGroups.splice(index, 1);
  26634. }
  26635. return index;
  26636. };
  26637. /**
  26638. * Removes the given multi-material from this scene.
  26639. * @param toRemove The multi-material to remove
  26640. * @returns The index of the removed multi-material
  26641. */
  26642. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26643. var index = this.multiMaterials.indexOf(toRemove);
  26644. if (index !== -1) {
  26645. this.multiMaterials.splice(index, 1);
  26646. }
  26647. return index;
  26648. };
  26649. /**
  26650. * Removes the given material from this scene.
  26651. * @param toRemove The material to remove
  26652. * @returns The index of the removed material
  26653. */
  26654. Scene.prototype.removeMaterial = function (toRemove) {
  26655. var index = this.materials.indexOf(toRemove);
  26656. if (index !== -1) {
  26657. this.materials.splice(index, 1);
  26658. }
  26659. return index;
  26660. };
  26661. /**
  26662. * Removes the given action manager from this scene.
  26663. * @param toRemove The action manager to remove
  26664. * @returns The index of the removed action manager
  26665. */
  26666. Scene.prototype.removeActionManager = function (toRemove) {
  26667. var index = this.actionManagers.indexOf(toRemove);
  26668. if (index !== -1) {
  26669. this.actionManagers.splice(index, 1);
  26670. }
  26671. return index;
  26672. };
  26673. /**
  26674. * Removes the given texture from this scene.
  26675. * @param toRemove The texture to remove
  26676. * @returns The index of the removed texture
  26677. */
  26678. Scene.prototype.removeTexture = function (toRemove) {
  26679. var index = this.textures.indexOf(toRemove);
  26680. if (index !== -1) {
  26681. this.textures.splice(index, 1);
  26682. }
  26683. return index;
  26684. };
  26685. /**
  26686. * Adds the given light to this scene
  26687. * @param newLight The light to add
  26688. */
  26689. Scene.prototype.addLight = function (newLight) {
  26690. this.lights.push(newLight);
  26691. this.sortLightsByPriority();
  26692. // Add light to all meshes (To support if the light is removed and then readded)
  26693. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26694. var mesh = _a[_i];
  26695. if (mesh._lightSources.indexOf(newLight) === -1) {
  26696. mesh._lightSources.push(newLight);
  26697. mesh._resyncLightSources();
  26698. }
  26699. }
  26700. this.onNewLightAddedObservable.notifyObservers(newLight);
  26701. };
  26702. /**
  26703. * Sorts the list list based on light priorities
  26704. */
  26705. Scene.prototype.sortLightsByPriority = function () {
  26706. if (this.requireLightSorting) {
  26707. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26708. }
  26709. };
  26710. /**
  26711. * Adds the given camera to this scene
  26712. * @param newCamera The camera to add
  26713. */
  26714. Scene.prototype.addCamera = function (newCamera) {
  26715. this.cameras.push(newCamera);
  26716. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26717. };
  26718. /**
  26719. * Adds the given skeleton to this scene
  26720. * @param newSkeleton The skeleton to add
  26721. */
  26722. Scene.prototype.addSkeleton = function (newSkeleton) {
  26723. this.skeletons.push(newSkeleton);
  26724. };
  26725. /**
  26726. * Adds the given particle system to this scene
  26727. * @param newParticleSystem The particle system to add
  26728. */
  26729. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26730. this.particleSystems.push(newParticleSystem);
  26731. };
  26732. /**
  26733. * Adds the given animation to this scene
  26734. * @param newAnimation The animation to add
  26735. */
  26736. Scene.prototype.addAnimation = function (newAnimation) {
  26737. this.animations.push(newAnimation);
  26738. };
  26739. /**
  26740. * Adds the given animation group to this scene.
  26741. * @param newAnimationGroup The animation group to add
  26742. */
  26743. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26744. this.animationGroups.push(newAnimationGroup);
  26745. };
  26746. /**
  26747. * Adds the given multi-material to this scene
  26748. * @param newMultiMaterial The multi-material to add
  26749. */
  26750. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26751. this.multiMaterials.push(newMultiMaterial);
  26752. };
  26753. /**
  26754. * Adds the given material to this scene
  26755. * @param newMaterial The material to add
  26756. */
  26757. Scene.prototype.addMaterial = function (newMaterial) {
  26758. this.materials.push(newMaterial);
  26759. };
  26760. /**
  26761. * Adds the given morph target to this scene
  26762. * @param newMorphTargetManager The morph target to add
  26763. */
  26764. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26765. this.morphTargetManagers.push(newMorphTargetManager);
  26766. };
  26767. /**
  26768. * Adds the given geometry to this scene
  26769. * @param newGeometry The geometry to add
  26770. */
  26771. Scene.prototype.addGeometry = function (newGeometry) {
  26772. this.geometries.push(newGeometry);
  26773. };
  26774. /**
  26775. * Adds the given action manager to this scene
  26776. * @param newActionManager The action manager to add
  26777. */
  26778. Scene.prototype.addActionManager = function (newActionManager) {
  26779. this.actionManagers.push(newActionManager);
  26780. };
  26781. /**
  26782. * Adds the given texture to this scene.
  26783. * @param newTexture The texture to add
  26784. */
  26785. Scene.prototype.addTexture = function (newTexture) {
  26786. this.textures.push(newTexture);
  26787. };
  26788. /**
  26789. * Switch active camera
  26790. * @param newCamera defines the new active camera
  26791. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26792. */
  26793. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26794. if (attachControl === void 0) { attachControl = true; }
  26795. var canvas = this._engine.getRenderingCanvas();
  26796. if (!canvas) {
  26797. return;
  26798. }
  26799. if (this.activeCamera) {
  26800. this.activeCamera.detachControl(canvas);
  26801. }
  26802. this.activeCamera = newCamera;
  26803. if (attachControl) {
  26804. newCamera.attachControl(canvas);
  26805. }
  26806. };
  26807. /**
  26808. * sets the active camera of the scene using its ID
  26809. * @param id defines the camera's ID
  26810. * @return the new active camera or null if none found.
  26811. */
  26812. Scene.prototype.setActiveCameraByID = function (id) {
  26813. var camera = this.getCameraByID(id);
  26814. if (camera) {
  26815. this.activeCamera = camera;
  26816. return camera;
  26817. }
  26818. return null;
  26819. };
  26820. /**
  26821. * sets the active camera of the scene using its name
  26822. * @param name defines the camera's name
  26823. * @returns the new active camera or null if none found.
  26824. */
  26825. Scene.prototype.setActiveCameraByName = function (name) {
  26826. var camera = this.getCameraByName(name);
  26827. if (camera) {
  26828. this.activeCamera = camera;
  26829. return camera;
  26830. }
  26831. return null;
  26832. };
  26833. /**
  26834. * get an animation group using its name
  26835. * @param name defines the material's name
  26836. * @return the animation group or null if none found.
  26837. */
  26838. Scene.prototype.getAnimationGroupByName = function (name) {
  26839. for (var index = 0; index < this.animationGroups.length; index++) {
  26840. if (this.animationGroups[index].name === name) {
  26841. return this.animationGroups[index];
  26842. }
  26843. }
  26844. return null;
  26845. };
  26846. /**
  26847. * get a material using its id
  26848. * @param id defines the material's ID
  26849. * @return the material or null if none found.
  26850. */
  26851. Scene.prototype.getMaterialByID = function (id) {
  26852. for (var index = 0; index < this.materials.length; index++) {
  26853. if (this.materials[index].id === id) {
  26854. return this.materials[index];
  26855. }
  26856. }
  26857. return null;
  26858. };
  26859. /**
  26860. * Gets a material using its name
  26861. * @param name defines the material's name
  26862. * @return the material or null if none found.
  26863. */
  26864. Scene.prototype.getMaterialByName = function (name) {
  26865. for (var index = 0; index < this.materials.length; index++) {
  26866. if (this.materials[index].name === name) {
  26867. return this.materials[index];
  26868. }
  26869. }
  26870. return null;
  26871. };
  26872. /**
  26873. * Gets a camera using its id
  26874. * @param id defines the id to look for
  26875. * @returns the camera or null if not found
  26876. */
  26877. Scene.prototype.getCameraByID = function (id) {
  26878. for (var index = 0; index < this.cameras.length; index++) {
  26879. if (this.cameras[index].id === id) {
  26880. return this.cameras[index];
  26881. }
  26882. }
  26883. return null;
  26884. };
  26885. /**
  26886. * Gets a camera using its unique id
  26887. * @param uniqueId defines the unique id to look for
  26888. * @returns the camera or null if not found
  26889. */
  26890. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26891. for (var index = 0; index < this.cameras.length; index++) {
  26892. if (this.cameras[index].uniqueId === uniqueId) {
  26893. return this.cameras[index];
  26894. }
  26895. }
  26896. return null;
  26897. };
  26898. /**
  26899. * Gets a camera using its name
  26900. * @param name defines the camera's name
  26901. * @return the camera or null if none found.
  26902. */
  26903. Scene.prototype.getCameraByName = function (name) {
  26904. for (var index = 0; index < this.cameras.length; index++) {
  26905. if (this.cameras[index].name === name) {
  26906. return this.cameras[index];
  26907. }
  26908. }
  26909. return null;
  26910. };
  26911. /**
  26912. * Gets a bone using its id
  26913. * @param id defines the bone's id
  26914. * @return the bone or null if not found
  26915. */
  26916. Scene.prototype.getBoneByID = function (id) {
  26917. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26918. var skeleton = this.skeletons[skeletonIndex];
  26919. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26920. if (skeleton.bones[boneIndex].id === id) {
  26921. return skeleton.bones[boneIndex];
  26922. }
  26923. }
  26924. }
  26925. return null;
  26926. };
  26927. /**
  26928. * Gets a bone using its id
  26929. * @param name defines the bone's name
  26930. * @return the bone or null if not found
  26931. */
  26932. Scene.prototype.getBoneByName = function (name) {
  26933. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26934. var skeleton = this.skeletons[skeletonIndex];
  26935. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26936. if (skeleton.bones[boneIndex].name === name) {
  26937. return skeleton.bones[boneIndex];
  26938. }
  26939. }
  26940. }
  26941. return null;
  26942. };
  26943. /**
  26944. * Gets a light node using its name
  26945. * @param name defines the the light's name
  26946. * @return the light or null if none found.
  26947. */
  26948. Scene.prototype.getLightByName = function (name) {
  26949. for (var index = 0; index < this.lights.length; index++) {
  26950. if (this.lights[index].name === name) {
  26951. return this.lights[index];
  26952. }
  26953. }
  26954. return null;
  26955. };
  26956. /**
  26957. * Gets a light node using its id
  26958. * @param id defines the light's id
  26959. * @return the light or null if none found.
  26960. */
  26961. Scene.prototype.getLightByID = function (id) {
  26962. for (var index = 0; index < this.lights.length; index++) {
  26963. if (this.lights[index].id === id) {
  26964. return this.lights[index];
  26965. }
  26966. }
  26967. return null;
  26968. };
  26969. /**
  26970. * Gets a light node using its scene-generated unique ID
  26971. * @param uniqueId defines the light's unique id
  26972. * @return the light or null if none found.
  26973. */
  26974. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26975. for (var index = 0; index < this.lights.length; index++) {
  26976. if (this.lights[index].uniqueId === uniqueId) {
  26977. return this.lights[index];
  26978. }
  26979. }
  26980. return null;
  26981. };
  26982. /**
  26983. * Gets a particle system by id
  26984. * @param id defines the particle system id
  26985. * @return the corresponding system or null if none found
  26986. */
  26987. Scene.prototype.getParticleSystemByID = function (id) {
  26988. for (var index = 0; index < this.particleSystems.length; index++) {
  26989. if (this.particleSystems[index].id === id) {
  26990. return this.particleSystems[index];
  26991. }
  26992. }
  26993. return null;
  26994. };
  26995. /**
  26996. * Gets a geometry using its ID
  26997. * @param id defines the geometry's id
  26998. * @return the geometry or null if none found.
  26999. */
  27000. Scene.prototype.getGeometryByID = function (id) {
  27001. for (var index = 0; index < this.geometries.length; index++) {
  27002. if (this.geometries[index].id === id) {
  27003. return this.geometries[index];
  27004. }
  27005. }
  27006. return null;
  27007. };
  27008. /**
  27009. * Add a new geometry to this scene
  27010. * @param geometry defines the geometry to be added to the scene.
  27011. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27012. * @return a boolean defining if the geometry was added or not
  27013. */
  27014. Scene.prototype.pushGeometry = function (geometry, force) {
  27015. if (!force && this.getGeometryByID(geometry.id)) {
  27016. return false;
  27017. }
  27018. this.geometries.push(geometry);
  27019. //notify the collision coordinator
  27020. if (this.collisionCoordinator) {
  27021. this.collisionCoordinator.onGeometryAdded(geometry);
  27022. }
  27023. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27024. return true;
  27025. };
  27026. /**
  27027. * Removes an existing geometry
  27028. * @param geometry defines the geometry to be removed from the scene
  27029. * @return a boolean defining if the geometry was removed or not
  27030. */
  27031. Scene.prototype.removeGeometry = function (geometry) {
  27032. var index = this.geometries.indexOf(geometry);
  27033. if (index > -1) {
  27034. this.geometries.splice(index, 1);
  27035. //notify the collision coordinator
  27036. if (this.collisionCoordinator) {
  27037. this.collisionCoordinator.onGeometryDeleted(geometry);
  27038. }
  27039. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27040. return true;
  27041. }
  27042. return false;
  27043. };
  27044. /**
  27045. * Gets the list of geometries attached to the scene
  27046. * @returns an array of Geometry
  27047. */
  27048. Scene.prototype.getGeometries = function () {
  27049. return this.geometries;
  27050. };
  27051. /**
  27052. * Gets the first added mesh found of a given ID
  27053. * @param id defines the id to search for
  27054. * @return the mesh found or null if not found at all
  27055. */
  27056. Scene.prototype.getMeshByID = function (id) {
  27057. for (var index = 0; index < this.meshes.length; index++) {
  27058. if (this.meshes[index].id === id) {
  27059. return this.meshes[index];
  27060. }
  27061. }
  27062. return null;
  27063. };
  27064. /**
  27065. * Gets a list of meshes using their id
  27066. * @param id defines the id to search for
  27067. * @returns a list of meshes
  27068. */
  27069. Scene.prototype.getMeshesByID = function (id) {
  27070. return this.meshes.filter(function (m) {
  27071. return m.id === id;
  27072. });
  27073. };
  27074. /**
  27075. * Gets the first added transform node found of a given ID
  27076. * @param id defines the id to search for
  27077. * @return the found transform node or null if not found at all.
  27078. */
  27079. Scene.prototype.getTransformNodeByID = function (id) {
  27080. for (var index = 0; index < this.transformNodes.length; index++) {
  27081. if (this.transformNodes[index].id === id) {
  27082. return this.transformNodes[index];
  27083. }
  27084. }
  27085. return null;
  27086. };
  27087. /**
  27088. * Gets a list of transform nodes using their id
  27089. * @param id defines the id to search for
  27090. * @returns a list of transform nodes
  27091. */
  27092. Scene.prototype.getTransformNodesByID = function (id) {
  27093. return this.transformNodes.filter(function (m) {
  27094. return m.id === id;
  27095. });
  27096. };
  27097. /**
  27098. * Gets a mesh with its auto-generated unique id
  27099. * @param uniqueId defines the unique id to search for
  27100. * @return the found mesh or null if not found at all.
  27101. */
  27102. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27103. for (var index = 0; index < this.meshes.length; index++) {
  27104. if (this.meshes[index].uniqueId === uniqueId) {
  27105. return this.meshes[index];
  27106. }
  27107. }
  27108. return null;
  27109. };
  27110. /**
  27111. * Gets a the last added mesh using a given id
  27112. * @param id defines the id to search for
  27113. * @return the found mesh or null if not found at all.
  27114. */
  27115. Scene.prototype.getLastMeshByID = function (id) {
  27116. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27117. if (this.meshes[index].id === id) {
  27118. return this.meshes[index];
  27119. }
  27120. }
  27121. return null;
  27122. };
  27123. /**
  27124. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27125. * @param id defines the id to search for
  27126. * @return the found node or null if not found at all
  27127. */
  27128. Scene.prototype.getLastEntryByID = function (id) {
  27129. var index;
  27130. for (index = this.meshes.length - 1; index >= 0; index--) {
  27131. if (this.meshes[index].id === id) {
  27132. return this.meshes[index];
  27133. }
  27134. }
  27135. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27136. if (this.transformNodes[index].id === id) {
  27137. return this.transformNodes[index];
  27138. }
  27139. }
  27140. for (index = this.cameras.length - 1; index >= 0; index--) {
  27141. if (this.cameras[index].id === id) {
  27142. return this.cameras[index];
  27143. }
  27144. }
  27145. for (index = this.lights.length - 1; index >= 0; index--) {
  27146. if (this.lights[index].id === id) {
  27147. return this.lights[index];
  27148. }
  27149. }
  27150. return null;
  27151. };
  27152. /**
  27153. * Gets a node (Mesh, Camera, Light) using a given id
  27154. * @param id defines the id to search for
  27155. * @return the found node or null if not found at all
  27156. */
  27157. Scene.prototype.getNodeByID = function (id) {
  27158. var mesh = this.getMeshByID(id);
  27159. if (mesh) {
  27160. return mesh;
  27161. }
  27162. var light = this.getLightByID(id);
  27163. if (light) {
  27164. return light;
  27165. }
  27166. var camera = this.getCameraByID(id);
  27167. if (camera) {
  27168. return camera;
  27169. }
  27170. var bone = this.getBoneByID(id);
  27171. return bone;
  27172. };
  27173. /**
  27174. * Gets a node (Mesh, Camera, Light) using a given name
  27175. * @param name defines the name to search for
  27176. * @return the found node or null if not found at all.
  27177. */
  27178. Scene.prototype.getNodeByName = function (name) {
  27179. var mesh = this.getMeshByName(name);
  27180. if (mesh) {
  27181. return mesh;
  27182. }
  27183. var light = this.getLightByName(name);
  27184. if (light) {
  27185. return light;
  27186. }
  27187. var camera = this.getCameraByName(name);
  27188. if (camera) {
  27189. return camera;
  27190. }
  27191. var bone = this.getBoneByName(name);
  27192. return bone;
  27193. };
  27194. /**
  27195. * Gets a mesh using a given name
  27196. * @param name defines the name to search for
  27197. * @return the found mesh or null if not found at all.
  27198. */
  27199. Scene.prototype.getMeshByName = function (name) {
  27200. for (var index = 0; index < this.meshes.length; index++) {
  27201. if (this.meshes[index].name === name) {
  27202. return this.meshes[index];
  27203. }
  27204. }
  27205. return null;
  27206. };
  27207. /**
  27208. * Gets a transform node using a given name
  27209. * @param name defines the name to search for
  27210. * @return the found transform node or null if not found at all.
  27211. */
  27212. Scene.prototype.getTransformNodeByName = function (name) {
  27213. for (var index = 0; index < this.transformNodes.length; index++) {
  27214. if (this.transformNodes[index].name === name) {
  27215. return this.transformNodes[index];
  27216. }
  27217. }
  27218. return null;
  27219. };
  27220. /**
  27221. * Gets a sound using a given name
  27222. * @param name defines the name to search for
  27223. * @return the found sound or null if not found at all.
  27224. */
  27225. Scene.prototype.getSoundByName = function (name) {
  27226. var index;
  27227. if (BABYLON.AudioEngine) {
  27228. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27229. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27230. return this.mainSoundTrack.soundCollection[index];
  27231. }
  27232. }
  27233. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27234. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27235. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27236. return this.soundTracks[sdIndex].soundCollection[index];
  27237. }
  27238. }
  27239. }
  27240. }
  27241. return null;
  27242. };
  27243. /**
  27244. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27245. * @param id defines the id to search for
  27246. * @return the found skeleton or null if not found at all.
  27247. */
  27248. Scene.prototype.getLastSkeletonByID = function (id) {
  27249. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27250. if (this.skeletons[index].id === id) {
  27251. return this.skeletons[index];
  27252. }
  27253. }
  27254. return null;
  27255. };
  27256. /**
  27257. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27258. * @param id defines the id to search for
  27259. * @return the found skeleton or null if not found at all.
  27260. */
  27261. Scene.prototype.getSkeletonById = function (id) {
  27262. for (var index = 0; index < this.skeletons.length; index++) {
  27263. if (this.skeletons[index].id === id) {
  27264. return this.skeletons[index];
  27265. }
  27266. }
  27267. return null;
  27268. };
  27269. /**
  27270. * Gets a skeleton using a given name
  27271. * @param name defines the name to search for
  27272. * @return the found skeleton or null if not found at all.
  27273. */
  27274. Scene.prototype.getSkeletonByName = function (name) {
  27275. for (var index = 0; index < this.skeletons.length; index++) {
  27276. if (this.skeletons[index].name === name) {
  27277. return this.skeletons[index];
  27278. }
  27279. }
  27280. return null;
  27281. };
  27282. /**
  27283. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27284. * @param id defines the id to search for
  27285. * @return the found morph target manager or null if not found at all.
  27286. */
  27287. Scene.prototype.getMorphTargetManagerById = function (id) {
  27288. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27289. if (this.morphTargetManagers[index].uniqueId === id) {
  27290. return this.morphTargetManagers[index];
  27291. }
  27292. }
  27293. return null;
  27294. };
  27295. /**
  27296. * Gets a boolean indicating if the given mesh is active
  27297. * @param mesh defines the mesh to look for
  27298. * @returns true if the mesh is in the active list
  27299. */
  27300. Scene.prototype.isActiveMesh = function (mesh) {
  27301. return (this._activeMeshes.indexOf(mesh) !== -1);
  27302. };
  27303. Object.defineProperty(Scene.prototype, "uid", {
  27304. /**
  27305. * Return a unique id as a string which can serve as an identifier for the scene
  27306. */
  27307. get: function () {
  27308. if (!this._uid) {
  27309. this._uid = BABYLON.Tools.RandomId();
  27310. }
  27311. return this._uid;
  27312. },
  27313. enumerable: true,
  27314. configurable: true
  27315. });
  27316. /**
  27317. * Add an externaly attached data from its key.
  27318. * This method call will fail and return false, if such key already exists.
  27319. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27320. * @param key the unique key that identifies the data
  27321. * @param data the data object to associate to the key for this Engine instance
  27322. * @return true if no such key were already present and the data was added successfully, false otherwise
  27323. */
  27324. Scene.prototype.addExternalData = function (key, data) {
  27325. if (!this._externalData) {
  27326. this._externalData = new BABYLON.StringDictionary();
  27327. }
  27328. return this._externalData.add(key, data);
  27329. };
  27330. /**
  27331. * Get an externaly attached data from its key
  27332. * @param key the unique key that identifies the data
  27333. * @return the associated data, if present (can be null), or undefined if not present
  27334. */
  27335. Scene.prototype.getExternalData = function (key) {
  27336. if (!this._externalData) {
  27337. return null;
  27338. }
  27339. return this._externalData.get(key);
  27340. };
  27341. /**
  27342. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27343. * @param key the unique key that identifies the data
  27344. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27345. * @return the associated data, can be null if the factory returned null.
  27346. */
  27347. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27348. if (!this._externalData) {
  27349. this._externalData = new BABYLON.StringDictionary();
  27350. }
  27351. return this._externalData.getOrAddWithFactory(key, factory);
  27352. };
  27353. /**
  27354. * Remove an externaly attached data from the Engine instance
  27355. * @param key the unique key that identifies the data
  27356. * @return true if the data was successfully removed, false if it doesn't exist
  27357. */
  27358. Scene.prototype.removeExternalData = function (key) {
  27359. return this._externalData.remove(key);
  27360. };
  27361. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27362. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27363. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27364. var step = _a[_i];
  27365. step.action(mesh, subMesh);
  27366. }
  27367. var material = subMesh.getMaterial();
  27368. if (material !== null && material !== undefined) {
  27369. // Render targets
  27370. if (material.getRenderTargetTextures !== undefined) {
  27371. if (this._processedMaterials.indexOf(material) === -1) {
  27372. this._processedMaterials.push(material);
  27373. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27374. }
  27375. }
  27376. // Dispatch
  27377. this._activeIndices.addCount(subMesh.indexCount, false);
  27378. this._renderingManager.dispatch(subMesh, mesh, material);
  27379. }
  27380. }
  27381. };
  27382. /**
  27383. * Clear the processed materials smart array preventing retention point in material dispose.
  27384. */
  27385. Scene.prototype.freeProcessedMaterials = function () {
  27386. this._processedMaterials.dispose();
  27387. };
  27388. /**
  27389. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27390. */
  27391. Scene.prototype.freeActiveMeshes = function () {
  27392. this._activeMeshes.dispose();
  27393. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27394. this.activeCamera._activeMeshes.dispose();
  27395. }
  27396. if (this.activeCameras) {
  27397. for (var i = 0; i < this.activeCameras.length; i++) {
  27398. var activeCamera = this.activeCameras[i];
  27399. if (activeCamera && activeCamera._activeMeshes) {
  27400. activeCamera._activeMeshes.dispose();
  27401. }
  27402. }
  27403. }
  27404. };
  27405. /**
  27406. * Clear the info related to rendering groups preventing retention points during dispose.
  27407. */
  27408. Scene.prototype.freeRenderingGroups = function () {
  27409. if (this._renderingManager) {
  27410. this._renderingManager.freeRenderingGroups();
  27411. }
  27412. if (this.textures) {
  27413. for (var i = 0; i < this.textures.length; i++) {
  27414. var texture = this.textures[i];
  27415. if (texture && texture.renderList) {
  27416. texture.freeRenderingGroups();
  27417. }
  27418. }
  27419. }
  27420. };
  27421. /** @hidden */
  27422. Scene.prototype._isInIntermediateRendering = function () {
  27423. return this._intermediateRendering;
  27424. };
  27425. /**
  27426. * Defines the current active mesh candidate provider
  27427. * @param provider defines the provider to use
  27428. */
  27429. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27430. this._activeMeshCandidateProvider = provider;
  27431. };
  27432. /**
  27433. * Gets the current active mesh candidate provider
  27434. * @returns the current active mesh candidate provider
  27435. */
  27436. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27437. return this._activeMeshCandidateProvider;
  27438. };
  27439. /**
  27440. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27441. * @returns the current scene
  27442. */
  27443. Scene.prototype.freezeActiveMeshes = function () {
  27444. if (!this.activeCamera) {
  27445. return this;
  27446. }
  27447. if (!this._frustumPlanes) {
  27448. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27449. }
  27450. this._evaluateActiveMeshes();
  27451. this._activeMeshesFrozen = true;
  27452. return this;
  27453. };
  27454. /**
  27455. * Use this function to restart evaluating active meshes on every frame
  27456. * @returns the current scene
  27457. */
  27458. Scene.prototype.unfreezeActiveMeshes = function () {
  27459. this._activeMeshesFrozen = false;
  27460. return this;
  27461. };
  27462. Scene.prototype._evaluateActiveMeshes = function () {
  27463. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27464. return;
  27465. }
  27466. if (!this.activeCamera) {
  27467. return;
  27468. }
  27469. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27470. this.activeCamera._activeMeshes.reset();
  27471. this._activeMeshes.reset();
  27472. this._renderingManager.reset();
  27473. this._processedMaterials.reset();
  27474. this._activeParticleSystems.reset();
  27475. this._activeSkeletons.reset();
  27476. this._softwareSkinnedMeshes.reset();
  27477. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27478. var step = _a[_i];
  27479. step.action();
  27480. }
  27481. // Meshes
  27482. var meshes;
  27483. var len;
  27484. var checkIsEnabled = true;
  27485. // Determine mesh candidates
  27486. if (this._activeMeshCandidateProvider !== undefined) {
  27487. // Use _activeMeshCandidateProvider
  27488. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27489. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27490. if (meshes !== undefined) {
  27491. len = meshes.length;
  27492. }
  27493. else {
  27494. len = 0;
  27495. }
  27496. }
  27497. else if (this._selectionOctree !== undefined) {
  27498. // Octree
  27499. var selection = this._selectionOctree.select(this._frustumPlanes);
  27500. meshes = selection.data;
  27501. len = selection.length;
  27502. }
  27503. else {
  27504. // Full scene traversal
  27505. len = this.meshes.length;
  27506. meshes = this.meshes;
  27507. }
  27508. // Check each mesh
  27509. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27510. mesh = meshes[meshIndex];
  27511. if (mesh.isBlocked) {
  27512. continue;
  27513. }
  27514. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27515. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27516. continue;
  27517. }
  27518. mesh.computeWorldMatrix();
  27519. // Intersections
  27520. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27521. this._meshesForIntersections.pushNoDuplicate(mesh);
  27522. }
  27523. // Switch to current LOD
  27524. meshLOD = mesh.getLOD(this.activeCamera);
  27525. if (meshLOD === undefined || meshLOD === null) {
  27526. continue;
  27527. }
  27528. mesh._preActivate();
  27529. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27530. this._activeMeshes.push(mesh);
  27531. this.activeCamera._activeMeshes.push(mesh);
  27532. mesh._activate(this._renderId);
  27533. if (meshLOD !== mesh) {
  27534. meshLOD._activate(this._renderId);
  27535. }
  27536. this._activeMesh(mesh, meshLOD);
  27537. }
  27538. }
  27539. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27540. // Particle systems
  27541. if (this.particlesEnabled) {
  27542. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27543. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27544. var particleSystem = this.particleSystems[particleIndex];
  27545. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27546. continue;
  27547. }
  27548. var emitter = particleSystem.emitter;
  27549. if (!emitter.position || emitter.isEnabled()) {
  27550. this._activeParticleSystems.push(particleSystem);
  27551. particleSystem.animate();
  27552. this._renderingManager.dispatchParticles(particleSystem);
  27553. }
  27554. }
  27555. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27556. }
  27557. };
  27558. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27559. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27560. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27561. mesh.skeleton.prepare();
  27562. }
  27563. if (!mesh.computeBonesUsingShaders) {
  27564. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27565. }
  27566. }
  27567. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27568. var step = _a[_i];
  27569. step.action(sourceMesh, mesh);
  27570. }
  27571. if (mesh !== undefined && mesh !== null
  27572. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27573. // Submeshes Octrees
  27574. var len;
  27575. var subMeshes;
  27576. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27577. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27578. len = intersections.length;
  27579. subMeshes = intersections.data;
  27580. }
  27581. else {
  27582. subMeshes = mesh.subMeshes;
  27583. len = subMeshes.length;
  27584. }
  27585. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27586. subMesh = subMeshes[subIndex];
  27587. this._evaluateSubMesh(subMesh, mesh);
  27588. }
  27589. }
  27590. };
  27591. /**
  27592. * Update the transform matrix to update from the current active camera
  27593. * @param force defines a boolean used to force the update even if cache is up to date
  27594. */
  27595. Scene.prototype.updateTransformMatrix = function (force) {
  27596. if (!this.activeCamera) {
  27597. return;
  27598. }
  27599. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27600. };
  27601. /**
  27602. * 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)
  27603. * @param alternateCamera defines the camera to use
  27604. */
  27605. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27606. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27607. };
  27608. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27609. if (camera && camera._skipRendering) {
  27610. return;
  27611. }
  27612. var engine = this._engine;
  27613. this.activeCamera = camera;
  27614. if (!this.activeCamera)
  27615. throw new Error("Active camera not set");
  27616. // Viewport
  27617. engine.setViewport(this.activeCamera.viewport);
  27618. // Camera
  27619. this.resetCachedMaterial();
  27620. this._renderId++;
  27621. this.updateTransformMatrix();
  27622. if (camera._alternateCamera) {
  27623. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27624. this._alternateRendering = true;
  27625. }
  27626. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27627. // Meshes
  27628. this._evaluateActiveMeshes();
  27629. // Software skinning
  27630. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27631. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27632. mesh.applySkeleton(mesh.skeleton);
  27633. }
  27634. // Render targets
  27635. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27636. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27637. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27638. }
  27639. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27640. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27641. }
  27642. if (this.renderTargetsEnabled) {
  27643. this._intermediateRendering = true;
  27644. if (this._renderTargets.length > 0) {
  27645. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27646. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27647. var renderTarget = this._renderTargets.data[renderIndex];
  27648. if (renderTarget._shouldRender()) {
  27649. this._renderId++;
  27650. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27651. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27652. }
  27653. }
  27654. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27655. this._renderId++;
  27656. }
  27657. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27658. var step = _a[_i];
  27659. step.action(this.activeCamera);
  27660. }
  27661. this._intermediateRendering = false;
  27662. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27663. }
  27664. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27665. // Prepare Frame
  27666. if (this.postProcessManager) {
  27667. this.postProcessManager._prepareFrame();
  27668. }
  27669. // Before Camera Draw
  27670. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27671. var step = _c[_b];
  27672. step.action(this.activeCamera);
  27673. }
  27674. // Render
  27675. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27676. this._renderingManager.render(null, null, true, true);
  27677. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27678. // After Camera Draw
  27679. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27680. var step = _e[_d];
  27681. step.action(this.activeCamera);
  27682. }
  27683. // Finalize frame
  27684. if (this.postProcessManager) {
  27685. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27686. }
  27687. // Reset some special arrays
  27688. this._renderTargets.reset();
  27689. this._alternateRendering = false;
  27690. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27691. };
  27692. Scene.prototype._processSubCameras = function (camera) {
  27693. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27694. this._renderForCamera(camera);
  27695. return;
  27696. }
  27697. // rig cameras
  27698. for (var index = 0; index < camera._rigCameras.length; index++) {
  27699. this._renderForCamera(camera._rigCameras[index], camera);
  27700. }
  27701. this.activeCamera = camera;
  27702. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27703. };
  27704. Scene.prototype._checkIntersections = function () {
  27705. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27706. var sourceMesh = this._meshesForIntersections.data[index];
  27707. if (!sourceMesh.actionManager) {
  27708. continue;
  27709. }
  27710. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27711. var action = sourceMesh.actionManager.actions[actionIndex];
  27712. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27713. var parameters = action.getTriggerParameter();
  27714. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27715. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27716. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27717. if (areIntersecting && currentIntersectionInProgress === -1) {
  27718. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27719. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27720. sourceMesh._intersectionsInProgress.push(otherMesh);
  27721. }
  27722. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27723. sourceMesh._intersectionsInProgress.push(otherMesh);
  27724. }
  27725. }
  27726. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27727. //They intersected, and now they don't.
  27728. //is this trigger an exit trigger? execute an event.
  27729. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27730. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27731. }
  27732. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27733. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27734. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27735. return otherMesh === parameterMesh;
  27736. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27737. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27738. }
  27739. }
  27740. }
  27741. }
  27742. }
  27743. };
  27744. /**
  27745. * Render the scene
  27746. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27747. */
  27748. Scene.prototype.render = function (updateCameras) {
  27749. if (updateCameras === void 0) { updateCameras = true; }
  27750. if (this.isDisposed) {
  27751. return;
  27752. }
  27753. // Register components that have been associated lately to the scene.
  27754. this._registerTransientComponents();
  27755. this._activeParticles.fetchNewFrame();
  27756. this._totalVertices.fetchNewFrame();
  27757. this._activeIndices.fetchNewFrame();
  27758. this._activeBones.fetchNewFrame();
  27759. this._meshesForIntersections.reset();
  27760. this.resetCachedMaterial();
  27761. this.onBeforeAnimationsObservable.notifyObservers(this);
  27762. // Actions
  27763. if (this.actionManager) {
  27764. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27765. }
  27766. //Simplification Queue
  27767. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27768. this.simplificationQueue.executeNext();
  27769. }
  27770. if (this._engine.isDeterministicLockStep()) {
  27771. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27772. var defaultFPS = (60.0 / 1000.0);
  27773. var defaultFrameTime = 1000 / 60; // frame time in MS
  27774. if (this._physicsEngine) {
  27775. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27776. }
  27777. var stepsTaken = 0;
  27778. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27779. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27780. internalSteps = Math.min(internalSteps, maxSubSteps);
  27781. do {
  27782. this.onBeforeStepObservable.notifyObservers(this);
  27783. // Animations
  27784. this._animationRatio = defaultFrameTime * defaultFPS;
  27785. this._animate();
  27786. this.onAfterAnimationsObservable.notifyObservers(this);
  27787. // Physics
  27788. if (this._physicsEngine) {
  27789. this.onBeforePhysicsObservable.notifyObservers(this);
  27790. this._physicsEngine._step(defaultFrameTime / 1000);
  27791. this.onAfterPhysicsObservable.notifyObservers(this);
  27792. }
  27793. this.onAfterStepObservable.notifyObservers(this);
  27794. this._currentStepId++;
  27795. stepsTaken++;
  27796. deltaTime -= defaultFrameTime;
  27797. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27798. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27799. }
  27800. else {
  27801. // Animations
  27802. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27803. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27804. this._animate();
  27805. this.onAfterAnimationsObservable.notifyObservers(this);
  27806. // Physics
  27807. if (this._physicsEngine) {
  27808. this.onBeforePhysicsObservable.notifyObservers(this);
  27809. this._physicsEngine._step(deltaTime / 1000.0);
  27810. this.onAfterPhysicsObservable.notifyObservers(this);
  27811. }
  27812. }
  27813. // Before camera update steps
  27814. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27815. var step = _a[_i];
  27816. step.action();
  27817. }
  27818. // Update Cameras
  27819. if (updateCameras) {
  27820. if (this.activeCameras.length > 0) {
  27821. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27822. var camera = this.activeCameras[cameraIndex];
  27823. camera.update();
  27824. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27825. // rig cameras
  27826. for (var index = 0; index < camera._rigCameras.length; index++) {
  27827. camera._rigCameras[index].update();
  27828. }
  27829. }
  27830. }
  27831. }
  27832. else if (this.activeCamera) {
  27833. this.activeCamera.update();
  27834. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27835. // rig cameras
  27836. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27837. this.activeCamera._rigCameras[index].update();
  27838. }
  27839. }
  27840. }
  27841. }
  27842. // Before render
  27843. this.onBeforeRenderObservable.notifyObservers(this);
  27844. // Customs render targets
  27845. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27846. var engine = this.getEngine();
  27847. var currentActiveCamera = this.activeCamera;
  27848. if (this.renderTargetsEnabled) {
  27849. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27850. this._intermediateRendering = true;
  27851. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27852. var renderTarget = this.customRenderTargets[customIndex];
  27853. if (renderTarget._shouldRender()) {
  27854. this._renderId++;
  27855. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27856. if (!this.activeCamera)
  27857. throw new Error("Active camera not set");
  27858. // Viewport
  27859. engine.setViewport(this.activeCamera.viewport);
  27860. // Camera
  27861. this.updateTransformMatrix();
  27862. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27863. }
  27864. }
  27865. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27866. this._intermediateRendering = false;
  27867. this._renderId++;
  27868. }
  27869. // Restore back buffer
  27870. if (this.customRenderTargets.length > 0) {
  27871. engine.restoreDefaultFramebuffer();
  27872. }
  27873. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27874. this.activeCamera = currentActiveCamera;
  27875. // Procedural textures
  27876. if (this.proceduralTexturesEnabled) {
  27877. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27878. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27879. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27880. if (proceduralTexture._shouldRender()) {
  27881. proceduralTexture.render();
  27882. }
  27883. }
  27884. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27885. }
  27886. // Clear
  27887. if (this.autoClearDepthAndStencil || this.autoClear) {
  27888. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27889. }
  27890. // Shadows
  27891. if (this.shadowsEnabled) {
  27892. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27893. var light = this.lights[lightIndex];
  27894. var shadowGenerator = light.getShadowGenerator();
  27895. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27896. var shadowMap = (shadowGenerator.getShadowMap());
  27897. if (this.textures.indexOf(shadowMap) !== -1) {
  27898. this._renderTargets.push(shadowMap);
  27899. }
  27900. }
  27901. }
  27902. }
  27903. // Depth renderer
  27904. for (var key in this._depthRenderer) {
  27905. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27906. }
  27907. // Geometry renderer
  27908. if (this._geometryBufferRenderer) {
  27909. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27910. }
  27911. // RenderPipeline
  27912. if (this._postProcessRenderPipelineManager) {
  27913. this._postProcessRenderPipelineManager.update();
  27914. }
  27915. // Multi-cameras?
  27916. if (this.activeCameras.length > 0) {
  27917. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27918. if (cameraIndex > 0) {
  27919. this._engine.clear(null, false, true, true);
  27920. }
  27921. this._processSubCameras(this.activeCameras[cameraIndex]);
  27922. }
  27923. }
  27924. else {
  27925. if (!this.activeCamera) {
  27926. throw new Error("No camera defined");
  27927. }
  27928. this._processSubCameras(this.activeCamera);
  27929. }
  27930. // Intersection checks
  27931. this._checkIntersections();
  27932. // Update the audio listener attached to the camera
  27933. if (BABYLON.AudioEngine) {
  27934. this._updateAudioParameters();
  27935. }
  27936. // After render
  27937. if (this.afterRender) {
  27938. this.afterRender();
  27939. }
  27940. this.onAfterRenderObservable.notifyObservers(this);
  27941. // Cleaning
  27942. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27943. var data = this._toBeDisposed.data[index];
  27944. if (data) {
  27945. data.dispose();
  27946. }
  27947. this._toBeDisposed[index] = null;
  27948. }
  27949. this._toBeDisposed.reset();
  27950. if (this.dumpNextRenderTargets) {
  27951. this.dumpNextRenderTargets = false;
  27952. }
  27953. this._activeBones.addCount(0, true);
  27954. this._activeIndices.addCount(0, true);
  27955. this._activeParticles.addCount(0, true);
  27956. };
  27957. Scene.prototype._updateAudioParameters = function () {
  27958. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27959. return;
  27960. }
  27961. var listeningCamera;
  27962. var audioEngine = BABYLON.Engine.audioEngine;
  27963. if (this.activeCameras.length > 0) {
  27964. listeningCamera = this.activeCameras[0];
  27965. }
  27966. else {
  27967. listeningCamera = this.activeCamera;
  27968. }
  27969. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27970. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27971. // for VR cameras
  27972. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27973. listeningCamera = listeningCamera.rigCameras[0];
  27974. }
  27975. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27976. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27977. cameraDirection.normalize();
  27978. // To avoid some errors on GearVR
  27979. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27980. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27981. }
  27982. var i;
  27983. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27984. var sound = this.mainSoundTrack.soundCollection[i];
  27985. if (sound.useCustomAttenuation) {
  27986. sound.updateDistanceFromListener();
  27987. }
  27988. }
  27989. for (i = 0; i < this.soundTracks.length; i++) {
  27990. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27991. sound = this.soundTracks[i].soundCollection[j];
  27992. if (sound.useCustomAttenuation) {
  27993. sound.updateDistanceFromListener();
  27994. }
  27995. }
  27996. }
  27997. }
  27998. };
  27999. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28000. // Audio
  28001. /**
  28002. * Gets or sets if audio support is enabled
  28003. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28004. */
  28005. get: function () {
  28006. return this._audioEnabled;
  28007. },
  28008. set: function (value) {
  28009. this._audioEnabled = value;
  28010. if (BABYLON.AudioEngine) {
  28011. if (this._audioEnabled) {
  28012. this._enableAudio();
  28013. }
  28014. else {
  28015. this._disableAudio();
  28016. }
  28017. }
  28018. },
  28019. enumerable: true,
  28020. configurable: true
  28021. });
  28022. Scene.prototype._disableAudio = function () {
  28023. var i;
  28024. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28025. this.mainSoundTrack.soundCollection[i].pause();
  28026. }
  28027. for (i = 0; i < this.soundTracks.length; i++) {
  28028. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28029. this.soundTracks[i].soundCollection[j].pause();
  28030. }
  28031. }
  28032. };
  28033. Scene.prototype._enableAudio = function () {
  28034. var i;
  28035. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28036. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28037. this.mainSoundTrack.soundCollection[i].play();
  28038. }
  28039. }
  28040. for (i = 0; i < this.soundTracks.length; i++) {
  28041. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28042. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28043. this.soundTracks[i].soundCollection[j].play();
  28044. }
  28045. }
  28046. }
  28047. };
  28048. Object.defineProperty(Scene.prototype, "headphone", {
  28049. /**
  28050. * Gets or sets if audio will be output to headphones
  28051. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28052. */
  28053. get: function () {
  28054. return this._headphone;
  28055. },
  28056. set: function (value) {
  28057. this._headphone = value;
  28058. if (BABYLON.AudioEngine) {
  28059. if (this._headphone) {
  28060. this._switchAudioModeForHeadphones();
  28061. }
  28062. else {
  28063. this._switchAudioModeForNormalSpeakers();
  28064. }
  28065. }
  28066. },
  28067. enumerable: true,
  28068. configurable: true
  28069. });
  28070. Scene.prototype._switchAudioModeForHeadphones = function () {
  28071. this.mainSoundTrack.switchPanningModelToHRTF();
  28072. for (var i = 0; i < this.soundTracks.length; i++) {
  28073. this.soundTracks[i].switchPanningModelToHRTF();
  28074. }
  28075. };
  28076. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28077. this.mainSoundTrack.switchPanningModelToEqualPower();
  28078. for (var i = 0; i < this.soundTracks.length; i++) {
  28079. this.soundTracks[i].switchPanningModelToEqualPower();
  28080. }
  28081. };
  28082. /**
  28083. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28084. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28085. * @returns the created depth renderer
  28086. */
  28087. Scene.prototype.enableDepthRenderer = function (camera) {
  28088. camera = camera || this.activeCamera;
  28089. if (!camera) {
  28090. throw "No camera available to enable depth renderer";
  28091. }
  28092. if (!this._depthRenderer[camera.id]) {
  28093. var textureType = 0;
  28094. if (this._engine.getCaps().textureHalfFloatRender) {
  28095. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28096. }
  28097. else if (this._engine.getCaps().textureFloatRender) {
  28098. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28099. }
  28100. else {
  28101. throw "Depth renderer does not support int texture type";
  28102. }
  28103. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28104. }
  28105. return this._depthRenderer[camera.id];
  28106. };
  28107. /**
  28108. * Disables a depth renderer for a given camera
  28109. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28110. */
  28111. Scene.prototype.disableDepthRenderer = function (camera) {
  28112. camera = camera || this.activeCamera;
  28113. if (!camera || !this._depthRenderer[camera.id]) {
  28114. return;
  28115. }
  28116. this._depthRenderer[camera.id].dispose();
  28117. delete this._depthRenderer[camera.id];
  28118. };
  28119. /**
  28120. * Enables a GeometryBufferRender and associates it with the scene
  28121. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28122. * @returns the GeometryBufferRenderer
  28123. */
  28124. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28125. if (ratio === void 0) { ratio = 1; }
  28126. if (this._geometryBufferRenderer) {
  28127. return this._geometryBufferRenderer;
  28128. }
  28129. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28130. if (!this._geometryBufferRenderer.isSupported) {
  28131. this._geometryBufferRenderer = null;
  28132. }
  28133. return this._geometryBufferRenderer;
  28134. };
  28135. /**
  28136. * Disables the GeometryBufferRender associated with the scene
  28137. */
  28138. Scene.prototype.disableGeometryBufferRenderer = function () {
  28139. if (!this._geometryBufferRenderer) {
  28140. return;
  28141. }
  28142. this._geometryBufferRenderer.dispose();
  28143. this._geometryBufferRenderer = null;
  28144. };
  28145. /**
  28146. * Freeze all materials
  28147. * A frozen material will not be updatable but should be faster to render
  28148. */
  28149. Scene.prototype.freezeMaterials = function () {
  28150. for (var i = 0; i < this.materials.length; i++) {
  28151. this.materials[i].freeze();
  28152. }
  28153. };
  28154. /**
  28155. * Unfreeze all materials
  28156. * A frozen material will not be updatable but should be faster to render
  28157. */
  28158. Scene.prototype.unfreezeMaterials = function () {
  28159. for (var i = 0; i < this.materials.length; i++) {
  28160. this.materials[i].unfreeze();
  28161. }
  28162. };
  28163. /**
  28164. * Releases all held ressources
  28165. */
  28166. Scene.prototype.dispose = function () {
  28167. this.beforeRender = null;
  28168. this.afterRender = null;
  28169. this.skeletons = [];
  28170. this.morphTargetManagers = [];
  28171. this._transientComponents = [];
  28172. this._isReadyForMeshStage.clear();
  28173. this._beforeEvaluateActiveMeshStage.clear();
  28174. this._evaluateSubMeshStage.clear();
  28175. this._activeMeshStage.clear();
  28176. this._cameraDrawRenderTargetStage.clear();
  28177. this._beforeCameraDrawStage.clear();
  28178. this._beforeRenderingGroupDrawStage.clear();
  28179. this._afterRenderingGroupDrawStage.clear();
  28180. this._afterCameraDrawStage.clear();
  28181. this._beforeCameraUpdateStage.clear();
  28182. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28183. var component = _a[_i];
  28184. component.dispose();
  28185. }
  28186. this.importedMeshesFiles = new Array();
  28187. this.stopAllAnimations();
  28188. this.resetCachedMaterial();
  28189. for (var key in this._depthRenderer) {
  28190. this._depthRenderer[key].dispose();
  28191. }
  28192. // Smart arrays
  28193. if (this.activeCamera) {
  28194. this.activeCamera._activeMeshes.dispose();
  28195. this.activeCamera = null;
  28196. }
  28197. this._activeMeshes.dispose();
  28198. this._renderingManager.dispose();
  28199. this._processedMaterials.dispose();
  28200. this._activeParticleSystems.dispose();
  28201. this._activeSkeletons.dispose();
  28202. this._softwareSkinnedMeshes.dispose();
  28203. this._renderTargets.dispose();
  28204. this._registeredForLateAnimationBindings.dispose();
  28205. this._meshesForIntersections.dispose();
  28206. this._toBeDisposed.dispose();
  28207. // Abort active requests
  28208. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28209. var request = _c[_b];
  28210. request.abort();
  28211. }
  28212. // Debug layer
  28213. if (this._debugLayer) {
  28214. this._debugLayer.hide();
  28215. }
  28216. // Events
  28217. this.onDisposeObservable.notifyObservers(this);
  28218. this.onDisposeObservable.clear();
  28219. this.onBeforeRenderObservable.clear();
  28220. this.onAfterRenderObservable.clear();
  28221. this.onBeforeRenderTargetsRenderObservable.clear();
  28222. this.onAfterRenderTargetsRenderObservable.clear();
  28223. this.onAfterStepObservable.clear();
  28224. this.onBeforeStepObservable.clear();
  28225. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28226. this.onAfterActiveMeshesEvaluationObservable.clear();
  28227. this.onBeforeParticlesRenderingObservable.clear();
  28228. this.onAfterParticlesRenderingObservable.clear();
  28229. this.onBeforeSpritesRenderingObservable.clear();
  28230. this.onAfterSpritesRenderingObservable.clear();
  28231. this.onBeforeDrawPhaseObservable.clear();
  28232. this.onAfterDrawPhaseObservable.clear();
  28233. this.onBeforePhysicsObservable.clear();
  28234. this.onAfterPhysicsObservable.clear();
  28235. this.onBeforeAnimationsObservable.clear();
  28236. this.onAfterAnimationsObservable.clear();
  28237. this.onDataLoadedObservable.clear();
  28238. this.detachControl();
  28239. // Release sounds & sounds tracks
  28240. if (BABYLON.AudioEngine) {
  28241. this.disposeSounds();
  28242. }
  28243. // VR Helper
  28244. if (this.VRHelper) {
  28245. this.VRHelper.dispose();
  28246. }
  28247. // Detach cameras
  28248. var canvas = this._engine.getRenderingCanvas();
  28249. if (canvas) {
  28250. var index;
  28251. for (index = 0; index < this.cameras.length; index++) {
  28252. this.cameras[index].detachControl(canvas);
  28253. }
  28254. }
  28255. // Release animation groups
  28256. while (this.animationGroups.length) {
  28257. this.animationGroups[0].dispose();
  28258. }
  28259. // Release lights
  28260. while (this.lights.length) {
  28261. this.lights[0].dispose();
  28262. }
  28263. // Release meshes
  28264. while (this.meshes.length) {
  28265. this.meshes[0].dispose(true);
  28266. }
  28267. while (this.transformNodes.length) {
  28268. this.removeTransformNode(this.transformNodes[0]);
  28269. }
  28270. // Release cameras
  28271. while (this.cameras.length) {
  28272. this.cameras[0].dispose();
  28273. }
  28274. // Release materials
  28275. if (this.defaultMaterial) {
  28276. this.defaultMaterial.dispose();
  28277. }
  28278. while (this.multiMaterials.length) {
  28279. this.multiMaterials[0].dispose();
  28280. }
  28281. while (this.materials.length) {
  28282. this.materials[0].dispose();
  28283. }
  28284. // Release particles
  28285. while (this.particleSystems.length) {
  28286. this.particleSystems[0].dispose();
  28287. }
  28288. // Release sprites
  28289. while (this.spriteManagers.length) {
  28290. this.spriteManagers[0].dispose();
  28291. }
  28292. // Release postProcesses
  28293. while (this.postProcesses.length) {
  28294. this.postProcesses[0].dispose();
  28295. }
  28296. // Release textures
  28297. while (this.textures.length) {
  28298. this.textures[0].dispose();
  28299. }
  28300. // Release UBO
  28301. this._sceneUbo.dispose();
  28302. if (this._alternateSceneUbo) {
  28303. this._alternateSceneUbo.dispose();
  28304. }
  28305. // Post-processes
  28306. this.postProcessManager.dispose();
  28307. if (this._postProcessRenderPipelineManager) {
  28308. this._postProcessRenderPipelineManager.dispose();
  28309. }
  28310. // Physics
  28311. if (this._physicsEngine) {
  28312. this.disablePhysicsEngine();
  28313. }
  28314. // Remove from engine
  28315. index = this._engine.scenes.indexOf(this);
  28316. if (index > -1) {
  28317. this._engine.scenes.splice(index, 1);
  28318. }
  28319. this._engine.wipeCaches(true);
  28320. this._isDisposed = true;
  28321. };
  28322. Object.defineProperty(Scene.prototype, "isDisposed", {
  28323. /**
  28324. * Gets if the scene is already disposed
  28325. */
  28326. get: function () {
  28327. return this._isDisposed;
  28328. },
  28329. enumerable: true,
  28330. configurable: true
  28331. });
  28332. /**
  28333. * Releases sounds & soundtracks
  28334. */
  28335. Scene.prototype.disposeSounds = function () {
  28336. if (!this._mainSoundTrack) {
  28337. return;
  28338. }
  28339. this.mainSoundTrack.dispose();
  28340. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28341. this.soundTracks[scIndex].dispose();
  28342. }
  28343. };
  28344. /**
  28345. * Call this function to reduce memory footprint of the scene.
  28346. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28347. */
  28348. Scene.prototype.clearCachedVertexData = function () {
  28349. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28350. var mesh = this.meshes[meshIndex];
  28351. var geometry = mesh.geometry;
  28352. if (geometry) {
  28353. geometry._indices = [];
  28354. for (var vbName in geometry._vertexBuffers) {
  28355. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28356. continue;
  28357. }
  28358. geometry._vertexBuffers[vbName]._buffer._data = null;
  28359. }
  28360. }
  28361. }
  28362. };
  28363. /**
  28364. * This function will remove the local cached buffer data from texture.
  28365. * It will save memory but will prevent the texture from being rebuilt
  28366. */
  28367. Scene.prototype.cleanCachedTextureBuffer = function () {
  28368. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28369. var baseTexture = _a[_i];
  28370. var buffer = baseTexture._buffer;
  28371. if (buffer) {
  28372. baseTexture._buffer = null;
  28373. }
  28374. }
  28375. };
  28376. // Octrees
  28377. /**
  28378. * Get the world extend vectors with an optional filter
  28379. *
  28380. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28381. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28382. */
  28383. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28384. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28385. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28386. filterPredicate = filterPredicate || (function () { return true; });
  28387. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28388. mesh.computeWorldMatrix(true);
  28389. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28390. return;
  28391. }
  28392. var boundingInfo = mesh.getBoundingInfo();
  28393. var minBox = boundingInfo.boundingBox.minimumWorld;
  28394. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28395. BABYLON.Tools.CheckExtends(minBox, min, max);
  28396. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28397. });
  28398. return {
  28399. min: min,
  28400. max: max
  28401. };
  28402. };
  28403. /**
  28404. * Creates or updates the octree used to boost selection (picking)
  28405. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28406. * @param maxCapacity defines the maximum capacity per leaf
  28407. * @param maxDepth defines the maximum depth of the octree
  28408. * @returns an octree of AbstractMesh
  28409. */
  28410. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28411. if (maxCapacity === void 0) { maxCapacity = 64; }
  28412. if (maxDepth === void 0) { maxDepth = 2; }
  28413. if (!this._selectionOctree) {
  28414. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28415. }
  28416. var worldExtends = this.getWorldExtends();
  28417. // Update octree
  28418. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28419. return this._selectionOctree;
  28420. };
  28421. // Picking
  28422. /**
  28423. * Creates a ray that can be used to pick in the scene
  28424. * @param x defines the x coordinate of the origin (on-screen)
  28425. * @param y defines the y coordinate of the origin (on-screen)
  28426. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28427. * @param camera defines the camera to use for the picking
  28428. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28429. * @returns a Ray
  28430. */
  28431. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28432. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28433. var result = BABYLON.Ray.Zero();
  28434. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28435. return result;
  28436. };
  28437. /**
  28438. * Creates a ray that can be used to pick in the scene
  28439. * @param x defines the x coordinate of the origin (on-screen)
  28440. * @param y defines the y coordinate of the origin (on-screen)
  28441. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28442. * @param result defines the ray where to store the picking ray
  28443. * @param camera defines the camera to use for the picking
  28444. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28445. * @returns the current scene
  28446. */
  28447. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28448. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28449. var engine = this._engine;
  28450. if (!camera) {
  28451. if (!this.activeCamera)
  28452. throw new Error("Active camera not set");
  28453. camera = this.activeCamera;
  28454. }
  28455. var cameraViewport = camera.viewport;
  28456. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28457. // Moving coordinates to local viewport world
  28458. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28459. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28460. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28461. return this;
  28462. };
  28463. /**
  28464. * Creates a ray that can be used to pick in the scene
  28465. * @param x defines the x coordinate of the origin (on-screen)
  28466. * @param y defines the y coordinate of the origin (on-screen)
  28467. * @param camera defines the camera to use for the picking
  28468. * @returns a Ray
  28469. */
  28470. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28471. var result = BABYLON.Ray.Zero();
  28472. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28473. return result;
  28474. };
  28475. /**
  28476. * Creates a ray that can be used to pick in the scene
  28477. * @param x defines the x coordinate of the origin (on-screen)
  28478. * @param y defines the y coordinate of the origin (on-screen)
  28479. * @param result defines the ray where to store the picking ray
  28480. * @param camera defines the camera to use for the picking
  28481. * @returns the current scene
  28482. */
  28483. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28484. if (!BABYLON.PickingInfo) {
  28485. return this;
  28486. }
  28487. var engine = this._engine;
  28488. if (!camera) {
  28489. if (!this.activeCamera)
  28490. throw new Error("Active camera not set");
  28491. camera = this.activeCamera;
  28492. }
  28493. var cameraViewport = camera.viewport;
  28494. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28495. var identity = BABYLON.Matrix.Identity();
  28496. // Moving coordinates to local viewport world
  28497. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28498. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28499. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28500. return this;
  28501. };
  28502. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28503. if (!BABYLON.PickingInfo) {
  28504. return null;
  28505. }
  28506. var pickingInfo = null;
  28507. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28508. var mesh = this.meshes[meshIndex];
  28509. if (predicate) {
  28510. if (!predicate(mesh)) {
  28511. continue;
  28512. }
  28513. }
  28514. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28515. continue;
  28516. }
  28517. var world = mesh.getWorldMatrix();
  28518. var ray = rayFunction(world);
  28519. var result = mesh.intersects(ray, fastCheck);
  28520. if (!result || !result.hit)
  28521. continue;
  28522. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28523. continue;
  28524. pickingInfo = result;
  28525. if (fastCheck) {
  28526. break;
  28527. }
  28528. }
  28529. return pickingInfo || new BABYLON.PickingInfo();
  28530. };
  28531. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28532. if (!BABYLON.PickingInfo) {
  28533. return null;
  28534. }
  28535. var pickingInfos = new Array();
  28536. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28537. var mesh = this.meshes[meshIndex];
  28538. if (predicate) {
  28539. if (!predicate(mesh)) {
  28540. continue;
  28541. }
  28542. }
  28543. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28544. continue;
  28545. }
  28546. var world = mesh.getWorldMatrix();
  28547. var ray = rayFunction(world);
  28548. var result = mesh.intersects(ray, false);
  28549. if (!result || !result.hit)
  28550. continue;
  28551. pickingInfos.push(result);
  28552. }
  28553. return pickingInfos;
  28554. };
  28555. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28556. if (!BABYLON.PickingInfo) {
  28557. return null;
  28558. }
  28559. var pickingInfo = null;
  28560. if (!camera) {
  28561. if (!this.activeCamera) {
  28562. return null;
  28563. }
  28564. camera = this.activeCamera;
  28565. }
  28566. if (this.spriteManagers.length > 0) {
  28567. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28568. var spriteManager = this.spriteManagers[spriteIndex];
  28569. if (!spriteManager.isPickable) {
  28570. continue;
  28571. }
  28572. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28573. if (!result || !result.hit)
  28574. continue;
  28575. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28576. continue;
  28577. pickingInfo = result;
  28578. if (fastCheck) {
  28579. break;
  28580. }
  28581. }
  28582. }
  28583. return pickingInfo || new BABYLON.PickingInfo();
  28584. };
  28585. /** Launch a ray to try to pick a mesh in the scene
  28586. * @param x position on screen
  28587. * @param y position on screen
  28588. * @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
  28589. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28590. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28591. * @returns a PickingInfo
  28592. */
  28593. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28594. var _this = this;
  28595. if (!BABYLON.PickingInfo) {
  28596. return null;
  28597. }
  28598. var result = this._internalPick(function (world) {
  28599. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28600. return _this._tempPickingRay;
  28601. }, predicate, fastCheck);
  28602. if (result) {
  28603. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28604. }
  28605. return result;
  28606. };
  28607. /** Launch a ray to try to pick a sprite in the scene
  28608. * @param x position on screen
  28609. * @param y position on screen
  28610. * @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
  28611. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28612. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28613. * @returns a PickingInfo
  28614. */
  28615. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28616. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28617. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28618. };
  28619. /** Use the given ray to pick a mesh in the scene
  28620. * @param ray The ray to use to pick meshes
  28621. * @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
  28622. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28623. * @returns a PickingInfo
  28624. */
  28625. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28626. var _this = this;
  28627. var result = this._internalPick(function (world) {
  28628. if (!_this._pickWithRayInverseMatrix) {
  28629. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28630. }
  28631. world.invertToRef(_this._pickWithRayInverseMatrix);
  28632. if (!_this._cachedRayForTransform) {
  28633. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28634. }
  28635. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28636. return _this._cachedRayForTransform;
  28637. }, predicate, fastCheck);
  28638. if (result) {
  28639. result.ray = ray;
  28640. }
  28641. return result;
  28642. };
  28643. /**
  28644. * Launch a ray to try to pick a mesh in the scene
  28645. * @param x X position on screen
  28646. * @param y Y position on screen
  28647. * @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
  28648. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28649. * @returns an array of PickingInfo
  28650. */
  28651. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28652. var _this = this;
  28653. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28654. };
  28655. /**
  28656. * Launch a ray to try to pick a mesh in the scene
  28657. * @param ray Ray to use
  28658. * @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
  28659. * @returns an array of PickingInfo
  28660. */
  28661. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28662. var _this = this;
  28663. return this._internalMultiPick(function (world) {
  28664. if (!_this._pickWithRayInverseMatrix) {
  28665. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28666. }
  28667. world.invertToRef(_this._pickWithRayInverseMatrix);
  28668. if (!_this._cachedRayForTransform) {
  28669. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28670. }
  28671. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28672. return _this._cachedRayForTransform;
  28673. }, predicate);
  28674. };
  28675. /**
  28676. * Force the value of meshUnderPointer
  28677. * @param mesh defines the mesh to use
  28678. */
  28679. Scene.prototype.setPointerOverMesh = function (mesh) {
  28680. if (this._pointerOverMesh === mesh) {
  28681. return;
  28682. }
  28683. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28684. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28685. }
  28686. this._pointerOverMesh = mesh;
  28687. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28688. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28689. }
  28690. };
  28691. /**
  28692. * Gets the mesh under the pointer
  28693. * @returns a Mesh or null if no mesh is under the pointer
  28694. */
  28695. Scene.prototype.getPointerOverMesh = function () {
  28696. return this._pointerOverMesh;
  28697. };
  28698. /**
  28699. * Force the sprite under the pointer
  28700. * @param sprite defines the sprite to use
  28701. */
  28702. Scene.prototype.setPointerOverSprite = function (sprite) {
  28703. if (this._pointerOverSprite === sprite) {
  28704. return;
  28705. }
  28706. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28707. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28708. }
  28709. this._pointerOverSprite = sprite;
  28710. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28711. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28712. }
  28713. };
  28714. /**
  28715. * Gets the sprite under the pointer
  28716. * @returns a Sprite or null if no sprite is under the pointer
  28717. */
  28718. Scene.prototype.getPointerOverSprite = function () {
  28719. return this._pointerOverSprite;
  28720. };
  28721. // Physics
  28722. /**
  28723. * Gets the current physics engine
  28724. * @returns a PhysicsEngine or null if none attached
  28725. */
  28726. Scene.prototype.getPhysicsEngine = function () {
  28727. return this._physicsEngine;
  28728. };
  28729. /**
  28730. * Enables physics to the current scene
  28731. * @param gravity defines the scene's gravity for the physics engine
  28732. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28733. * @return a boolean indicating if the physics engine was initialized
  28734. */
  28735. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28736. if (gravity === void 0) { gravity = null; }
  28737. if (this._physicsEngine) {
  28738. return true;
  28739. }
  28740. try {
  28741. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28742. return true;
  28743. }
  28744. catch (e) {
  28745. BABYLON.Tools.Error(e.message);
  28746. return false;
  28747. }
  28748. };
  28749. /**
  28750. * Disables and disposes the physics engine associated with the scene
  28751. */
  28752. Scene.prototype.disablePhysicsEngine = function () {
  28753. if (!this._physicsEngine) {
  28754. return;
  28755. }
  28756. this._physicsEngine.dispose();
  28757. this._physicsEngine = null;
  28758. };
  28759. /**
  28760. * Gets a boolean indicating if there is an active physics engine
  28761. * @returns a boolean indicating if there is an active physics engine
  28762. */
  28763. Scene.prototype.isPhysicsEnabled = function () {
  28764. return this._physicsEngine !== undefined;
  28765. };
  28766. /**
  28767. * Deletes a physics compound impostor
  28768. * @param compound defines the compound to delete
  28769. */
  28770. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28771. var mesh = compound.parts[0].mesh;
  28772. if (mesh.physicsImpostor) {
  28773. mesh.physicsImpostor.dispose( /*true*/);
  28774. mesh.physicsImpostor = null;
  28775. }
  28776. };
  28777. // Misc.
  28778. /** @hidden */
  28779. Scene.prototype._rebuildGeometries = function () {
  28780. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28781. var geometry = _a[_i];
  28782. geometry._rebuild();
  28783. }
  28784. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28785. var mesh = _c[_b];
  28786. mesh._rebuild();
  28787. }
  28788. if (this.postProcessManager) {
  28789. this.postProcessManager._rebuild();
  28790. }
  28791. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28792. var component = _e[_d];
  28793. component.rebuild();
  28794. }
  28795. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28796. var system = _g[_f];
  28797. system.rebuild();
  28798. }
  28799. if (this._postProcessRenderPipelineManager) {
  28800. this._postProcessRenderPipelineManager._rebuild();
  28801. }
  28802. };
  28803. /** @hidden */
  28804. Scene.prototype._rebuildTextures = function () {
  28805. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28806. var texture = _a[_i];
  28807. texture._rebuild();
  28808. }
  28809. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28810. };
  28811. /**
  28812. * Creates a default light for the scene.
  28813. * @param replace Whether to replace the existing lights in the scene.
  28814. */
  28815. Scene.prototype.createDefaultLight = function (replace) {
  28816. if (replace === void 0) { replace = false; }
  28817. // Dispose existing light in replace mode.
  28818. if (replace) {
  28819. if (this.lights) {
  28820. for (var i = 0; i < this.lights.length; i++) {
  28821. this.lights[i].dispose();
  28822. }
  28823. }
  28824. }
  28825. // Light
  28826. if (this.lights.length === 0) {
  28827. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28828. }
  28829. };
  28830. /**
  28831. * Creates a default camera for the scene.
  28832. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28833. * @param replace Whether to replace the existing active camera in the scene.
  28834. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28835. */
  28836. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28837. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28838. if (replace === void 0) { replace = false; }
  28839. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28840. // Dispose existing camera in replace mode.
  28841. if (replace) {
  28842. if (this.activeCamera) {
  28843. this.activeCamera.dispose();
  28844. this.activeCamera = null;
  28845. }
  28846. }
  28847. // Camera
  28848. if (!this.activeCamera) {
  28849. var worldExtends = this.getWorldExtends();
  28850. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28851. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28852. var camera;
  28853. var radius = worldSize.length() * 1.5;
  28854. // empty scene scenario!
  28855. if (!isFinite(radius)) {
  28856. radius = 1;
  28857. worldCenter.copyFromFloats(0, 0, 0);
  28858. }
  28859. if (createArcRotateCamera) {
  28860. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28861. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28862. arcRotateCamera.wheelPrecision = 100 / radius;
  28863. camera = arcRotateCamera;
  28864. }
  28865. else {
  28866. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28867. freeCamera.setTarget(worldCenter);
  28868. camera = freeCamera;
  28869. }
  28870. camera.minZ = radius * 0.01;
  28871. camera.maxZ = radius * 1000;
  28872. camera.speed = radius * 0.2;
  28873. this.activeCamera = camera;
  28874. var canvas = this.getEngine().getRenderingCanvas();
  28875. if (attachCameraControls && canvas) {
  28876. camera.attachControl(canvas);
  28877. }
  28878. }
  28879. };
  28880. /**
  28881. * Creates a default camera and a default light
  28882. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28883. * @param replace defines if the camera and/or light will replace the existing ones
  28884. * @param attachCameraControls defines if attachControl will be called on the new camera
  28885. */
  28886. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28887. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28888. if (replace === void 0) { replace = false; }
  28889. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28890. this.createDefaultLight(replace);
  28891. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28892. };
  28893. /**
  28894. * Creates a new sky box
  28895. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28896. * @param environmentTexture defines the texture to use as environment texture
  28897. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28898. * @param scale defines the overall scale of the skybox
  28899. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28900. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28901. * @returns a new mesh holding the sky box
  28902. */
  28903. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28904. if (pbr === void 0) { pbr = false; }
  28905. if (scale === void 0) { scale = 1000; }
  28906. if (blur === void 0) { blur = 0; }
  28907. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28908. if (!environmentTexture) {
  28909. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28910. return null;
  28911. }
  28912. if (setGlobalEnvTexture) {
  28913. if (environmentTexture) {
  28914. this.environmentTexture = environmentTexture;
  28915. }
  28916. }
  28917. // Skybox
  28918. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28919. if (pbr) {
  28920. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28921. hdrSkyboxMaterial.backFaceCulling = false;
  28922. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28923. if (hdrSkyboxMaterial.reflectionTexture) {
  28924. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28925. }
  28926. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28927. hdrSkyboxMaterial.disableLighting = true;
  28928. hdrSkyboxMaterial.twoSidedLighting = true;
  28929. hdrSkybox.infiniteDistance = true;
  28930. hdrSkybox.material = hdrSkyboxMaterial;
  28931. }
  28932. else {
  28933. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28934. skyboxMaterial.backFaceCulling = false;
  28935. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28936. if (skyboxMaterial.reflectionTexture) {
  28937. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28938. }
  28939. skyboxMaterial.disableLighting = true;
  28940. hdrSkybox.infiniteDistance = true;
  28941. hdrSkybox.material = skyboxMaterial;
  28942. }
  28943. return hdrSkybox;
  28944. };
  28945. /**
  28946. * Creates a new environment
  28947. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28948. * @param options defines the options you can use to configure the environment
  28949. * @returns the new EnvironmentHelper
  28950. */
  28951. Scene.prototype.createDefaultEnvironment = function (options) {
  28952. if (BABYLON.EnvironmentHelper) {
  28953. return new BABYLON.EnvironmentHelper(options, this);
  28954. }
  28955. return null;
  28956. };
  28957. /**
  28958. * Creates a new VREXperienceHelper
  28959. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28960. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28961. * @returns a new VREXperienceHelper
  28962. */
  28963. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28964. if (webVROptions === void 0) { webVROptions = {}; }
  28965. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28966. };
  28967. // Tags
  28968. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28969. if (tagsQuery === undefined) {
  28970. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28971. return list;
  28972. }
  28973. var listByTags = [];
  28974. forEach = forEach || (function (item) { return; });
  28975. for (var i in list) {
  28976. var item = list[i];
  28977. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28978. listByTags.push(item);
  28979. forEach(item);
  28980. }
  28981. }
  28982. return listByTags;
  28983. };
  28984. /**
  28985. * Get a list of meshes by tags
  28986. * @param tagsQuery defines the tags query to use
  28987. * @param forEach defines a predicate used to filter results
  28988. * @returns an array of Mesh
  28989. */
  28990. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28991. return this._getByTags(this.meshes, tagsQuery, forEach);
  28992. };
  28993. /**
  28994. * Get a list of cameras by tags
  28995. * @param tagsQuery defines the tags query to use
  28996. * @param forEach defines a predicate used to filter results
  28997. * @returns an array of Camera
  28998. */
  28999. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29000. return this._getByTags(this.cameras, tagsQuery, forEach);
  29001. };
  29002. /**
  29003. * Get a list of lights by tags
  29004. * @param tagsQuery defines the tags query to use
  29005. * @param forEach defines a predicate used to filter results
  29006. * @returns an array of Light
  29007. */
  29008. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29009. return this._getByTags(this.lights, tagsQuery, forEach);
  29010. };
  29011. /**
  29012. * Get a list of materials by tags
  29013. * @param tagsQuery defines the tags query to use
  29014. * @param forEach defines a predicate used to filter results
  29015. * @returns an array of Material
  29016. */
  29017. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29018. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29019. };
  29020. /**
  29021. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29022. * This allowed control for front to back rendering or reversly depending of the special needs.
  29023. *
  29024. * @param renderingGroupId The rendering group id corresponding to its index
  29025. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29026. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29027. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29028. */
  29029. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29030. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29031. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29032. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29033. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29034. };
  29035. /**
  29036. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29037. *
  29038. * @param renderingGroupId The rendering group id corresponding to its index
  29039. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29040. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29041. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29042. */
  29043. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29044. if (depth === void 0) { depth = true; }
  29045. if (stencil === void 0) { stencil = true; }
  29046. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29047. };
  29048. /**
  29049. * Will flag all materials as dirty to trigger new shader compilation
  29050. * @param flag defines the flag used to specify which material part must be marked as dirty
  29051. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29052. */
  29053. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29054. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29055. var material = _a[_i];
  29056. if (predicate && !predicate(material)) {
  29057. continue;
  29058. }
  29059. material.markAsDirty(flag);
  29060. }
  29061. };
  29062. /** @hidden */
  29063. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29064. var _this = this;
  29065. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29066. this._activeRequests.push(request);
  29067. request.onCompleteObservable.add(function (request) {
  29068. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29069. });
  29070. return request;
  29071. };
  29072. /** @hidden */
  29073. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29074. var _this = this;
  29075. return new Promise(function (resolve, reject) {
  29076. _this._loadFile(url, function (data) {
  29077. resolve(data);
  29078. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29079. reject(exception);
  29080. });
  29081. });
  29082. };
  29083. // Statics
  29084. Scene._FOGMODE_NONE = 0;
  29085. Scene._FOGMODE_EXP = 1;
  29086. Scene._FOGMODE_EXP2 = 2;
  29087. Scene._FOGMODE_LINEAR = 3;
  29088. Scene._uniqueIdCounter = 0;
  29089. /**
  29090. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29091. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29092. */
  29093. Scene.MinDeltaTime = 1.0;
  29094. /**
  29095. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29096. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29097. */
  29098. Scene.MaxDeltaTime = 1000.0;
  29099. /** The distance in pixel that you have to move to prevent some events */
  29100. Scene.DragMovementThreshold = 10; // in pixels
  29101. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29102. Scene.LongPressDelay = 500; // in milliseconds
  29103. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29104. Scene.DoubleClickDelay = 300; // in milliseconds
  29105. /** If you need to check double click without raising a single click at first click, enable this flag */
  29106. Scene.ExclusiveDoubleClickMode = false;
  29107. return Scene;
  29108. }(BABYLON.AbstractScene));
  29109. BABYLON.Scene = Scene;
  29110. })(BABYLON || (BABYLON = {}));
  29111. //# sourceMappingURL=babylon.scene.js.map
  29112. var BABYLON;
  29113. (function (BABYLON) {
  29114. /**
  29115. * Set of assets to keep when moving a scene into an asset container.
  29116. */
  29117. var KeepAssets = /** @class */ (function (_super) {
  29118. __extends(KeepAssets, _super);
  29119. function KeepAssets() {
  29120. return _super !== null && _super.apply(this, arguments) || this;
  29121. }
  29122. return KeepAssets;
  29123. }(BABYLON.AbstractScene));
  29124. BABYLON.KeepAssets = KeepAssets;
  29125. /**
  29126. * Container with a set of assets that can be added or removed from a scene.
  29127. */
  29128. var AssetContainer = /** @class */ (function (_super) {
  29129. __extends(AssetContainer, _super);
  29130. /**
  29131. * Instantiates an AssetContainer.
  29132. * @param scene The scene the AssetContainer belongs to.
  29133. */
  29134. function AssetContainer(scene) {
  29135. var _this = _super.call(this) || this;
  29136. _this.scene = scene;
  29137. return _this;
  29138. }
  29139. /**
  29140. * Adds all the assets from the container to the scene.
  29141. */
  29142. AssetContainer.prototype.addAllToScene = function () {
  29143. var _this = this;
  29144. this.cameras.forEach(function (o) {
  29145. _this.scene.addCamera(o);
  29146. });
  29147. this.lights.forEach(function (o) {
  29148. _this.scene.addLight(o);
  29149. });
  29150. this.meshes.forEach(function (o) {
  29151. _this.scene.addMesh(o);
  29152. });
  29153. this.skeletons.forEach(function (o) {
  29154. _this.scene.addSkeleton(o);
  29155. });
  29156. this.animations.forEach(function (o) {
  29157. _this.scene.addAnimation(o);
  29158. });
  29159. this.animationGroups.forEach(function (o) {
  29160. _this.scene.addAnimationGroup(o);
  29161. });
  29162. this.multiMaterials.forEach(function (o) {
  29163. _this.scene.addMultiMaterial(o);
  29164. });
  29165. this.materials.forEach(function (o) {
  29166. _this.scene.addMaterial(o);
  29167. });
  29168. this.morphTargetManagers.forEach(function (o) {
  29169. _this.scene.addMorphTargetManager(o);
  29170. });
  29171. this.geometries.forEach(function (o) {
  29172. _this.scene.addGeometry(o);
  29173. });
  29174. this.transformNodes.forEach(function (o) {
  29175. _this.scene.addTransformNode(o);
  29176. });
  29177. this.actionManagers.forEach(function (o) {
  29178. _this.scene.addActionManager(o);
  29179. });
  29180. this.sounds.forEach(function (o) {
  29181. o.play();
  29182. o.autoplay = true;
  29183. _this.scene.mainSoundTrack.AddSound(o);
  29184. });
  29185. this.textures.forEach(function (o) {
  29186. _this.scene.addTexture(o);
  29187. });
  29188. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29189. var component = _a[_i];
  29190. component.addFromContainer(this.scene);
  29191. }
  29192. };
  29193. /**
  29194. * Removes all the assets in the container from the scene
  29195. */
  29196. AssetContainer.prototype.removeAllFromScene = function () {
  29197. var _this = this;
  29198. this.cameras.forEach(function (o) {
  29199. _this.scene.removeCamera(o);
  29200. });
  29201. this.lights.forEach(function (o) {
  29202. _this.scene.removeLight(o);
  29203. });
  29204. this.meshes.forEach(function (o) {
  29205. _this.scene.removeMesh(o);
  29206. });
  29207. this.skeletons.forEach(function (o) {
  29208. _this.scene.removeSkeleton(o);
  29209. });
  29210. this.animations.forEach(function (o) {
  29211. _this.scene.removeAnimation(o);
  29212. });
  29213. this.animationGroups.forEach(function (o) {
  29214. _this.scene.removeAnimationGroup(o);
  29215. });
  29216. this.multiMaterials.forEach(function (o) {
  29217. _this.scene.removeMultiMaterial(o);
  29218. });
  29219. this.materials.forEach(function (o) {
  29220. _this.scene.removeMaterial(o);
  29221. });
  29222. this.morphTargetManagers.forEach(function (o) {
  29223. _this.scene.removeMorphTargetManager(o);
  29224. });
  29225. this.geometries.forEach(function (o) {
  29226. _this.scene.removeGeometry(o);
  29227. });
  29228. this.transformNodes.forEach(function (o) {
  29229. _this.scene.removeTransformNode(o);
  29230. });
  29231. this.actionManagers.forEach(function (o) {
  29232. _this.scene.removeActionManager(o);
  29233. });
  29234. this.sounds.forEach(function (o) {
  29235. o.stop();
  29236. o.autoplay = false;
  29237. _this.scene.mainSoundTrack.RemoveSound(o);
  29238. });
  29239. this.textures.forEach(function (o) {
  29240. _this.scene.removeTexture(o);
  29241. });
  29242. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29243. var component = _a[_i];
  29244. component.removeFromContainer(this.scene);
  29245. }
  29246. };
  29247. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29248. if (!sourceAssets) {
  29249. return;
  29250. }
  29251. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29252. var asset = sourceAssets_1[_i];
  29253. var move = true;
  29254. if (keepAssets) {
  29255. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29256. var keepAsset = keepAssets_1[_a];
  29257. if (asset === keepAsset) {
  29258. move = false;
  29259. break;
  29260. }
  29261. }
  29262. }
  29263. if (move) {
  29264. targetAssets.push(asset);
  29265. }
  29266. }
  29267. };
  29268. /**
  29269. * Removes all the assets contained in the scene and adds them to the container.
  29270. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29271. */
  29272. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29273. if (keepAssets === undefined) {
  29274. keepAssets = new KeepAssets();
  29275. }
  29276. for (var key in this) {
  29277. if (this.hasOwnProperty(key)) {
  29278. this[key] = this[key] || [];
  29279. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29280. }
  29281. }
  29282. this.removeAllFromScene();
  29283. };
  29284. /**
  29285. * 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.
  29286. * @returns the root mesh
  29287. */
  29288. AssetContainer.prototype.createRootMesh = function () {
  29289. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29290. this.meshes.forEach(function (m) {
  29291. if (!m.parent) {
  29292. rootMesh.addChild(m);
  29293. }
  29294. });
  29295. this.meshes.unshift(rootMesh);
  29296. return rootMesh;
  29297. };
  29298. return AssetContainer;
  29299. }(BABYLON.AbstractScene));
  29300. BABYLON.AssetContainer = AssetContainer;
  29301. })(BABYLON || (BABYLON = {}));
  29302. //# sourceMappingURL=babylon.assetContainer.js.map
  29303. var BABYLON;
  29304. (function (BABYLON) {
  29305. var Buffer = /** @class */ (function () {
  29306. /**
  29307. * Constructor
  29308. * @param engine the engine
  29309. * @param data the data to use for this buffer
  29310. * @param updatable whether the data is updatable
  29311. * @param stride the stride (optional)
  29312. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29313. * @param instanced whether the buffer is instanced (optional)
  29314. * @param useBytes set to true if the stride in in bytes (optional)
  29315. */
  29316. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29317. if (stride === void 0) { stride = 0; }
  29318. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29319. if (instanced === void 0) { instanced = false; }
  29320. if (useBytes === void 0) { useBytes = false; }
  29321. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29322. this._engine = engine.getScene().getEngine();
  29323. }
  29324. else {
  29325. this._engine = engine;
  29326. }
  29327. this._updatable = updatable;
  29328. this._instanced = instanced;
  29329. this._data = data;
  29330. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29331. if (!postponeInternalCreation) { // by default
  29332. this.create();
  29333. }
  29334. }
  29335. /**
  29336. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29337. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29338. * @param offset defines offset in the buffer (0 by default)
  29339. * @param size defines the size in floats of attributes (position is 3 for instance)
  29340. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29341. * @param instanced defines if the vertex buffer contains indexed data
  29342. * @param useBytes defines if the offset and stride are in bytes
  29343. * @returns the new vertex buffer
  29344. */
  29345. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29346. if (useBytes === void 0) { useBytes = false; }
  29347. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29348. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29349. // a lot of these parameters are ignored as they are overriden by the buffer
  29350. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29351. };
  29352. // Properties
  29353. Buffer.prototype.isUpdatable = function () {
  29354. return this._updatable;
  29355. };
  29356. Buffer.prototype.getData = function () {
  29357. return this._data;
  29358. };
  29359. Buffer.prototype.getBuffer = function () {
  29360. return this._buffer;
  29361. };
  29362. /**
  29363. * Gets the stride in float32 units (i.e. byte stride / 4).
  29364. * May not be an integer if the byte stride is not divisible by 4.
  29365. * DEPRECATED. Use byteStride instead.
  29366. * @returns the stride in float32 units
  29367. */
  29368. Buffer.prototype.getStrideSize = function () {
  29369. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29370. };
  29371. // Methods
  29372. Buffer.prototype.create = function (data) {
  29373. if (data === void 0) { data = null; }
  29374. if (!data && this._buffer) {
  29375. return; // nothing to do
  29376. }
  29377. data = data || this._data;
  29378. if (!data) {
  29379. return;
  29380. }
  29381. if (!this._buffer) { // create buffer
  29382. if (this._updatable) {
  29383. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29384. this._data = data;
  29385. }
  29386. else {
  29387. this._buffer = this._engine.createVertexBuffer(data);
  29388. }
  29389. }
  29390. else if (this._updatable) { // update buffer
  29391. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29392. this._data = data;
  29393. }
  29394. };
  29395. Buffer.prototype._rebuild = function () {
  29396. this._buffer = null;
  29397. this.create(this._data);
  29398. };
  29399. Buffer.prototype.update = function (data) {
  29400. this.create(data);
  29401. };
  29402. /**
  29403. * Updates the data directly.
  29404. * @param data the new data
  29405. * @param offset the new offset
  29406. * @param vertexCount the vertex count (optional)
  29407. * @param useBytes set to true if the offset is in bytes
  29408. */
  29409. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29410. if (useBytes === void 0) { useBytes = false; }
  29411. if (!this._buffer) {
  29412. return;
  29413. }
  29414. if (this._updatable) { // update buffer
  29415. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29416. this._data = null;
  29417. }
  29418. };
  29419. Buffer.prototype.dispose = function () {
  29420. if (!this._buffer) {
  29421. return;
  29422. }
  29423. if (this._engine._releaseBuffer(this._buffer)) {
  29424. this._buffer = null;
  29425. }
  29426. };
  29427. return Buffer;
  29428. }());
  29429. BABYLON.Buffer = Buffer;
  29430. })(BABYLON || (BABYLON = {}));
  29431. //# sourceMappingURL=babylon.buffer.js.map
  29432. var BABYLON;
  29433. (function (BABYLON) {
  29434. var VertexBuffer = /** @class */ (function () {
  29435. /**
  29436. * Constructor
  29437. * @param engine the engine
  29438. * @param data the data to use for this vertex buffer
  29439. * @param kind the vertex buffer kind
  29440. * @param updatable whether the data is updatable
  29441. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29442. * @param stride the stride (optional)
  29443. * @param instanced whether the buffer is instanced (optional)
  29444. * @param offset the offset of the data (optional)
  29445. * @param size the number of components (optional)
  29446. * @param type the type of the component (optional)
  29447. * @param normalized whether the data contains normalized data (optional)
  29448. * @param useBytes set to true if stride and offset are in bytes (optional)
  29449. */
  29450. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29451. if (normalized === void 0) { normalized = false; }
  29452. if (useBytes === void 0) { useBytes = false; }
  29453. if (data instanceof BABYLON.Buffer) {
  29454. this._buffer = data;
  29455. this._ownsBuffer = false;
  29456. }
  29457. else {
  29458. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29459. this._ownsBuffer = true;
  29460. }
  29461. this._kind = kind;
  29462. if (type == undefined) {
  29463. var data_1 = this.getData();
  29464. this.type = VertexBuffer.FLOAT;
  29465. if (data_1 instanceof Int8Array)
  29466. this.type = VertexBuffer.BYTE;
  29467. else if (data_1 instanceof Uint8Array)
  29468. this.type = VertexBuffer.UNSIGNED_BYTE;
  29469. else if (data_1 instanceof Int16Array)
  29470. this.type = VertexBuffer.SHORT;
  29471. else if (data_1 instanceof Uint16Array)
  29472. this.type = VertexBuffer.UNSIGNED_SHORT;
  29473. else if (data_1 instanceof Int32Array)
  29474. this.type = VertexBuffer.INT;
  29475. else if (data_1 instanceof Uint32Array)
  29476. this.type = VertexBuffer.UNSIGNED_INT;
  29477. }
  29478. else {
  29479. this.type = type;
  29480. }
  29481. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29482. if (useBytes) {
  29483. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29484. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29485. this.byteOffset = offset || 0;
  29486. }
  29487. else {
  29488. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29489. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29490. this.byteOffset = (offset || 0) * typeByteLength;
  29491. }
  29492. this.normalized = normalized;
  29493. this._instanced = instanced !== undefined ? instanced : false;
  29494. this._instanceDivisor = instanced ? 1 : 0;
  29495. }
  29496. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29497. /**
  29498. * Gets or sets the instance divisor when in instanced mode
  29499. */
  29500. get: function () {
  29501. return this._instanceDivisor;
  29502. },
  29503. set: function (value) {
  29504. this._instanceDivisor = value;
  29505. if (value == 0) {
  29506. this._instanced = false;
  29507. }
  29508. else {
  29509. this._instanced = true;
  29510. }
  29511. },
  29512. enumerable: true,
  29513. configurable: true
  29514. });
  29515. VertexBuffer.prototype._rebuild = function () {
  29516. if (!this._buffer) {
  29517. return;
  29518. }
  29519. this._buffer._rebuild();
  29520. };
  29521. /**
  29522. * Returns the kind of the VertexBuffer (string).
  29523. */
  29524. VertexBuffer.prototype.getKind = function () {
  29525. return this._kind;
  29526. };
  29527. // Properties
  29528. /**
  29529. * Boolean : is the VertexBuffer updatable ?
  29530. */
  29531. VertexBuffer.prototype.isUpdatable = function () {
  29532. return this._buffer.isUpdatable();
  29533. };
  29534. /**
  29535. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29536. */
  29537. VertexBuffer.prototype.getData = function () {
  29538. return this._buffer.getData();
  29539. };
  29540. /**
  29541. * Returns the WebGLBuffer associated to the VertexBuffer.
  29542. */
  29543. VertexBuffer.prototype.getBuffer = function () {
  29544. return this._buffer.getBuffer();
  29545. };
  29546. /**
  29547. * Returns the stride as a multiple of the type byte length.
  29548. * DEPRECATED. Use byteStride instead.
  29549. */
  29550. VertexBuffer.prototype.getStrideSize = function () {
  29551. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29552. };
  29553. /**
  29554. * Returns the offset as a multiple of the type byte length.
  29555. * DEPRECATED. Use byteOffset instead.
  29556. */
  29557. VertexBuffer.prototype.getOffset = function () {
  29558. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29559. };
  29560. /**
  29561. * Returns the number of components per vertex attribute (integer).
  29562. */
  29563. VertexBuffer.prototype.getSize = function () {
  29564. return this._size;
  29565. };
  29566. /**
  29567. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29568. */
  29569. VertexBuffer.prototype.getIsInstanced = function () {
  29570. return this._instanced;
  29571. };
  29572. /**
  29573. * Returns the instancing divisor, zero for non-instanced (integer).
  29574. */
  29575. VertexBuffer.prototype.getInstanceDivisor = function () {
  29576. return this._instanceDivisor;
  29577. };
  29578. // Methods
  29579. /**
  29580. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29581. * Returns the created WebGLBuffer.
  29582. */
  29583. VertexBuffer.prototype.create = function (data) {
  29584. return this._buffer.create(data);
  29585. };
  29586. /**
  29587. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29588. * This function will create a new buffer if the current one is not updatable
  29589. * Returns the updated WebGLBuffer.
  29590. */
  29591. VertexBuffer.prototype.update = function (data) {
  29592. return this._buffer.update(data);
  29593. };
  29594. /**
  29595. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29596. * Returns the directly updated WebGLBuffer.
  29597. * @param data the new data
  29598. * @param offset the new offset
  29599. * @param useBytes set to true if the offset is in bytes
  29600. */
  29601. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29602. if (useBytes === void 0) { useBytes = false; }
  29603. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29604. };
  29605. /**
  29606. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29607. */
  29608. VertexBuffer.prototype.dispose = function () {
  29609. if (this._ownsBuffer) {
  29610. this._buffer.dispose();
  29611. }
  29612. };
  29613. /**
  29614. * Enumerates each value of this vertex buffer as numbers.
  29615. * @param count the number of values to enumerate
  29616. * @param callback the callback function called for each value
  29617. */
  29618. VertexBuffer.prototype.forEach = function (count, callback) {
  29619. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29620. };
  29621. Object.defineProperty(VertexBuffer, "PositionKind", {
  29622. get: function () {
  29623. return VertexBuffer._PositionKind;
  29624. },
  29625. enumerable: true,
  29626. configurable: true
  29627. });
  29628. Object.defineProperty(VertexBuffer, "NormalKind", {
  29629. get: function () {
  29630. return VertexBuffer._NormalKind;
  29631. },
  29632. enumerable: true,
  29633. configurable: true
  29634. });
  29635. Object.defineProperty(VertexBuffer, "TangentKind", {
  29636. get: function () {
  29637. return VertexBuffer._TangentKind;
  29638. },
  29639. enumerable: true,
  29640. configurable: true
  29641. });
  29642. Object.defineProperty(VertexBuffer, "UVKind", {
  29643. get: function () {
  29644. return VertexBuffer._UVKind;
  29645. },
  29646. enumerable: true,
  29647. configurable: true
  29648. });
  29649. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29650. get: function () {
  29651. return VertexBuffer._UV2Kind;
  29652. },
  29653. enumerable: true,
  29654. configurable: true
  29655. });
  29656. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29657. get: function () {
  29658. return VertexBuffer._UV3Kind;
  29659. },
  29660. enumerable: true,
  29661. configurable: true
  29662. });
  29663. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29664. get: function () {
  29665. return VertexBuffer._UV4Kind;
  29666. },
  29667. enumerable: true,
  29668. configurable: true
  29669. });
  29670. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29671. get: function () {
  29672. return VertexBuffer._UV5Kind;
  29673. },
  29674. enumerable: true,
  29675. configurable: true
  29676. });
  29677. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29678. get: function () {
  29679. return VertexBuffer._UV6Kind;
  29680. },
  29681. enumerable: true,
  29682. configurable: true
  29683. });
  29684. Object.defineProperty(VertexBuffer, "ColorKind", {
  29685. get: function () {
  29686. return VertexBuffer._ColorKind;
  29687. },
  29688. enumerable: true,
  29689. configurable: true
  29690. });
  29691. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29692. get: function () {
  29693. return VertexBuffer._MatricesIndicesKind;
  29694. },
  29695. enumerable: true,
  29696. configurable: true
  29697. });
  29698. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29699. get: function () {
  29700. return VertexBuffer._MatricesWeightsKind;
  29701. },
  29702. enumerable: true,
  29703. configurable: true
  29704. });
  29705. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29706. get: function () {
  29707. return VertexBuffer._MatricesIndicesExtraKind;
  29708. },
  29709. enumerable: true,
  29710. configurable: true
  29711. });
  29712. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29713. get: function () {
  29714. return VertexBuffer._MatricesWeightsExtraKind;
  29715. },
  29716. enumerable: true,
  29717. configurable: true
  29718. });
  29719. /**
  29720. * Deduces the stride given a kind.
  29721. * @param kind The kind string to deduce
  29722. * @returns The deduced stride
  29723. */
  29724. VertexBuffer.DeduceStride = function (kind) {
  29725. switch (kind) {
  29726. case VertexBuffer.UVKind:
  29727. case VertexBuffer.UV2Kind:
  29728. case VertexBuffer.UV3Kind:
  29729. case VertexBuffer.UV4Kind:
  29730. case VertexBuffer.UV5Kind:
  29731. case VertexBuffer.UV6Kind:
  29732. return 2;
  29733. case VertexBuffer.NormalKind:
  29734. case VertexBuffer.PositionKind:
  29735. return 3;
  29736. case VertexBuffer.ColorKind:
  29737. case VertexBuffer.MatricesIndicesKind:
  29738. case VertexBuffer.MatricesIndicesExtraKind:
  29739. case VertexBuffer.MatricesWeightsKind:
  29740. case VertexBuffer.MatricesWeightsExtraKind:
  29741. case VertexBuffer.TangentKind:
  29742. return 4;
  29743. default:
  29744. throw new Error("Invalid kind '" + kind + "'");
  29745. }
  29746. };
  29747. /**
  29748. * Gets the byte length of the given type.
  29749. * @param type the type
  29750. * @returns the number of bytes
  29751. */
  29752. VertexBuffer.GetTypeByteLength = function (type) {
  29753. switch (type) {
  29754. case VertexBuffer.BYTE:
  29755. case VertexBuffer.UNSIGNED_BYTE:
  29756. return 1;
  29757. case VertexBuffer.SHORT:
  29758. case VertexBuffer.UNSIGNED_SHORT:
  29759. return 2;
  29760. case VertexBuffer.INT:
  29761. case VertexBuffer.FLOAT:
  29762. return 4;
  29763. default:
  29764. throw new Error("Invalid type '" + type + "'");
  29765. }
  29766. };
  29767. /**
  29768. * Enumerates each value of the given parameters as numbers.
  29769. * @param data the data to enumerate
  29770. * @param byteOffset the byte offset of the data
  29771. * @param byteStride the byte stride of the data
  29772. * @param componentCount the number of components per element
  29773. * @param componentType the type of the component
  29774. * @param count the total number of components
  29775. * @param normalized whether the data is normalized
  29776. * @param callback the callback function called for each value
  29777. */
  29778. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29779. if (data instanceof Array) {
  29780. var offset = byteOffset / 4;
  29781. var stride = byteStride / 4;
  29782. for (var index = 0; index < count; index += componentCount) {
  29783. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29784. callback(data[offset + componentIndex], index + componentIndex);
  29785. }
  29786. offset += stride;
  29787. }
  29788. }
  29789. else {
  29790. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29791. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29792. for (var index = 0; index < count; index += componentCount) {
  29793. var componentByteOffset = byteOffset;
  29794. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29795. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29796. callback(value, index + componentIndex);
  29797. componentByteOffset += componentByteLength;
  29798. }
  29799. byteOffset += byteStride;
  29800. }
  29801. }
  29802. };
  29803. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29804. switch (type) {
  29805. case VertexBuffer.BYTE: {
  29806. var value = dataView.getInt8(byteOffset);
  29807. if (normalized) {
  29808. value = Math.max(value / 127, -1);
  29809. }
  29810. return value;
  29811. }
  29812. case VertexBuffer.UNSIGNED_BYTE: {
  29813. var value = dataView.getUint8(byteOffset);
  29814. if (normalized) {
  29815. value = value / 255;
  29816. }
  29817. return value;
  29818. }
  29819. case VertexBuffer.SHORT: {
  29820. var value = dataView.getInt16(byteOffset, true);
  29821. if (normalized) {
  29822. value = Math.max(value / 16383, -1);
  29823. }
  29824. return value;
  29825. }
  29826. case VertexBuffer.UNSIGNED_SHORT: {
  29827. var value = dataView.getUint16(byteOffset, true);
  29828. if (normalized) {
  29829. value = value / 65535;
  29830. }
  29831. return value;
  29832. }
  29833. case VertexBuffer.FLOAT: {
  29834. return dataView.getFloat32(byteOffset, true);
  29835. }
  29836. default: {
  29837. throw new Error("Invalid component type " + type);
  29838. }
  29839. }
  29840. };
  29841. /**
  29842. * The byte type.
  29843. */
  29844. VertexBuffer.BYTE = 5120;
  29845. /**
  29846. * The unsigned byte type.
  29847. */
  29848. VertexBuffer.UNSIGNED_BYTE = 5121;
  29849. /**
  29850. * The short type.
  29851. */
  29852. VertexBuffer.SHORT = 5122;
  29853. /**
  29854. * The unsigned short type.
  29855. */
  29856. VertexBuffer.UNSIGNED_SHORT = 5123;
  29857. /**
  29858. * The integer type.
  29859. */
  29860. VertexBuffer.INT = 5124;
  29861. /**
  29862. * The unsigned integer type.
  29863. */
  29864. VertexBuffer.UNSIGNED_INT = 5125;
  29865. /**
  29866. * The float type.
  29867. */
  29868. VertexBuffer.FLOAT = 5126;
  29869. // Enums
  29870. VertexBuffer._PositionKind = "position";
  29871. VertexBuffer._NormalKind = "normal";
  29872. VertexBuffer._TangentKind = "tangent";
  29873. VertexBuffer._UVKind = "uv";
  29874. VertexBuffer._UV2Kind = "uv2";
  29875. VertexBuffer._UV3Kind = "uv3";
  29876. VertexBuffer._UV4Kind = "uv4";
  29877. VertexBuffer._UV5Kind = "uv5";
  29878. VertexBuffer._UV6Kind = "uv6";
  29879. VertexBuffer._ColorKind = "color";
  29880. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29881. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29882. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29883. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29884. return VertexBuffer;
  29885. }());
  29886. BABYLON.VertexBuffer = VertexBuffer;
  29887. })(BABYLON || (BABYLON = {}));
  29888. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29889. var BABYLON;
  29890. (function (BABYLON) {
  29891. /**
  29892. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29893. */
  29894. var DummyInternalTextureTracker = /** @class */ (function () {
  29895. function DummyInternalTextureTracker() {
  29896. /**
  29897. * Gets or set the previous tracker in the list
  29898. */
  29899. this.previous = null;
  29900. /**
  29901. * Gets or set the next tracker in the list
  29902. */
  29903. this.next = null;
  29904. }
  29905. return DummyInternalTextureTracker;
  29906. }());
  29907. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29908. })(BABYLON || (BABYLON = {}));
  29909. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29910. var BABYLON;
  29911. (function (BABYLON) {
  29912. /**
  29913. * Class used to store data associated with WebGL texture data for the engine
  29914. * This class should not be used directly
  29915. */
  29916. var InternalTexture = /** @class */ (function () {
  29917. /**
  29918. * Creates a new InternalTexture
  29919. * @param engine defines the engine to use
  29920. * @param dataSource defines the type of data that will be used
  29921. */
  29922. function InternalTexture(engine, dataSource) {
  29923. /**
  29924. * Observable called when the texture is loaded
  29925. */
  29926. this.onLoadedObservable = new BABYLON.Observable();
  29927. /**
  29928. * Gets or set the previous tracker in the list
  29929. */
  29930. this.previous = null;
  29931. /**
  29932. * Gets or set the next tracker in the list
  29933. */
  29934. this.next = null;
  29935. // Private
  29936. /** @hidden */
  29937. this._initialSlot = -1;
  29938. /** @hidden */
  29939. this._designatedSlot = -1;
  29940. /** @hidden */
  29941. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29942. /** @hidden */
  29943. this._comparisonFunction = 0;
  29944. /** @hidden */
  29945. this._sphericalPolynomial = null;
  29946. /** @hidden */
  29947. this._lodGenerationScale = 0;
  29948. /** @hidden */
  29949. this._lodGenerationOffset = 0;
  29950. /** @hidden */
  29951. this._isRGBD = false;
  29952. /** @hidden */
  29953. this._references = 1;
  29954. this._engine = engine;
  29955. this._dataSource = dataSource;
  29956. this._webGLTexture = engine._createTexture();
  29957. }
  29958. /**
  29959. * Gets the Engine the texture belongs to.
  29960. * @returns The babylon engine
  29961. */
  29962. InternalTexture.prototype.getEngine = function () {
  29963. return this._engine;
  29964. };
  29965. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29966. /**
  29967. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29968. */
  29969. get: function () {
  29970. return this._dataSource;
  29971. },
  29972. enumerable: true,
  29973. configurable: true
  29974. });
  29975. /**
  29976. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29977. */
  29978. InternalTexture.prototype.incrementReferences = function () {
  29979. this._references++;
  29980. };
  29981. /**
  29982. * Change the size of the texture (not the size of the content)
  29983. * @param width defines the new width
  29984. * @param height defines the new height
  29985. * @param depth defines the new depth (1 by default)
  29986. */
  29987. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29988. if (depth === void 0) { depth = 1; }
  29989. this.width = width;
  29990. this.height = height;
  29991. this.depth = depth;
  29992. this.baseWidth = width;
  29993. this.baseHeight = height;
  29994. this.baseDepth = depth;
  29995. this._size = width * height * depth;
  29996. };
  29997. /** @hidden */
  29998. InternalTexture.prototype._rebuild = function () {
  29999. var _this = this;
  30000. var proxy;
  30001. this.isReady = false;
  30002. this._cachedCoordinatesMode = null;
  30003. this._cachedWrapU = null;
  30004. this._cachedWrapV = null;
  30005. this._cachedAnisotropicFilteringLevel = null;
  30006. switch (this._dataSource) {
  30007. case InternalTexture.DATASOURCE_TEMP:
  30008. return;
  30009. case InternalTexture.DATASOURCE_URL:
  30010. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30011. _this.isReady = true;
  30012. }, null, this._buffer, undefined, this.format);
  30013. proxy._swapAndDie(this);
  30014. return;
  30015. case InternalTexture.DATASOURCE_RAW:
  30016. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30017. proxy._swapAndDie(this);
  30018. this.isReady = true;
  30019. return;
  30020. case InternalTexture.DATASOURCE_RAW3D:
  30021. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30022. proxy._swapAndDie(this);
  30023. this.isReady = true;
  30024. return;
  30025. case InternalTexture.DATASOURCE_DYNAMIC:
  30026. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30027. proxy._swapAndDie(this);
  30028. // The engine will make sure to update content so no need to flag it as isReady = true
  30029. return;
  30030. case InternalTexture.DATASOURCE_RENDERTARGET:
  30031. var options = new BABYLON.RenderTargetCreationOptions();
  30032. options.generateDepthBuffer = this._generateDepthBuffer;
  30033. options.generateMipMaps = this.generateMipMaps;
  30034. options.generateStencilBuffer = this._generateStencilBuffer;
  30035. options.samplingMode = this.samplingMode;
  30036. options.type = this.type;
  30037. if (this.isCube) {
  30038. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30039. }
  30040. else {
  30041. var size = {
  30042. width: this.width,
  30043. height: this.height
  30044. };
  30045. proxy = this._engine.createRenderTargetTexture(size, options);
  30046. }
  30047. proxy._swapAndDie(this);
  30048. this.isReady = true;
  30049. return;
  30050. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30051. var depthTextureOptions = {
  30052. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30053. comparisonFunction: this._comparisonFunction,
  30054. generateStencil: this._generateStencilBuffer,
  30055. isCube: this.isCube
  30056. };
  30057. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30058. proxy._swapAndDie(this);
  30059. this.isReady = true;
  30060. return;
  30061. case InternalTexture.DATASOURCE_CUBE:
  30062. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30063. _this.isReady = true;
  30064. }, null, this.format, this._extension);
  30065. proxy._swapAndDie(this);
  30066. return;
  30067. case InternalTexture.DATASOURCE_CUBERAW:
  30068. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30069. proxy._swapAndDie(this);
  30070. this.isReady = true;
  30071. return;
  30072. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30073. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30074. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30075. _this.isReady = true;
  30076. });
  30077. proxy._swapAndDie(this);
  30078. return;
  30079. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30080. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30081. if (proxy) {
  30082. proxy._swapAndDie(_this);
  30083. }
  30084. _this.isReady = true;
  30085. }, null, this.format, this._extension);
  30086. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30087. return;
  30088. }
  30089. };
  30090. InternalTexture.prototype._swapAndDie = function (target) {
  30091. target._webGLTexture = this._webGLTexture;
  30092. if (this._framebuffer) {
  30093. target._framebuffer = this._framebuffer;
  30094. }
  30095. if (this._depthStencilBuffer) {
  30096. target._depthStencilBuffer = this._depthStencilBuffer;
  30097. }
  30098. if (this._lodTextureHigh) {
  30099. if (target._lodTextureHigh) {
  30100. target._lodTextureHigh.dispose();
  30101. }
  30102. target._lodTextureHigh = this._lodTextureHigh;
  30103. }
  30104. if (this._lodTextureMid) {
  30105. if (target._lodTextureMid) {
  30106. target._lodTextureMid.dispose();
  30107. }
  30108. target._lodTextureMid = this._lodTextureMid;
  30109. }
  30110. if (this._lodTextureLow) {
  30111. if (target._lodTextureLow) {
  30112. target._lodTextureLow.dispose();
  30113. }
  30114. target._lodTextureLow = this._lodTextureLow;
  30115. }
  30116. var cache = this._engine.getLoadedTexturesCache();
  30117. var index = cache.indexOf(this);
  30118. if (index !== -1) {
  30119. cache.splice(index, 1);
  30120. }
  30121. };
  30122. /**
  30123. * Dispose the current allocated resources
  30124. */
  30125. InternalTexture.prototype.dispose = function () {
  30126. if (!this._webGLTexture) {
  30127. return;
  30128. }
  30129. this._references--;
  30130. if (this._references === 0) {
  30131. this._engine._releaseTexture(this);
  30132. this._webGLTexture = null;
  30133. this.previous = null;
  30134. this.next = null;
  30135. }
  30136. };
  30137. /**
  30138. * The source of the texture data is unknown
  30139. */
  30140. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30141. /**
  30142. * Texture data comes from an URL
  30143. */
  30144. InternalTexture.DATASOURCE_URL = 1;
  30145. /**
  30146. * Texture data is only used for temporary storage
  30147. */
  30148. InternalTexture.DATASOURCE_TEMP = 2;
  30149. /**
  30150. * Texture data comes from raw data (ArrayBuffer)
  30151. */
  30152. InternalTexture.DATASOURCE_RAW = 3;
  30153. /**
  30154. * Texture content is dynamic (video or dynamic texture)
  30155. */
  30156. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30157. /**
  30158. * Texture content is generated by rendering to it
  30159. */
  30160. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30161. /**
  30162. * Texture content is part of a multi render target process
  30163. */
  30164. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30165. /**
  30166. * Texture data comes from a cube data file
  30167. */
  30168. InternalTexture.DATASOURCE_CUBE = 7;
  30169. /**
  30170. * Texture data comes from a raw cube data
  30171. */
  30172. InternalTexture.DATASOURCE_CUBERAW = 8;
  30173. /**
  30174. * Texture data come from a prefiltered cube data file
  30175. */
  30176. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30177. /**
  30178. * Texture content is raw 3D data
  30179. */
  30180. InternalTexture.DATASOURCE_RAW3D = 10;
  30181. /**
  30182. * Texture content is a depth texture
  30183. */
  30184. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30185. /**
  30186. * Texture data comes from a raw cube data encoded with RGBD
  30187. */
  30188. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30189. return InternalTexture;
  30190. }());
  30191. BABYLON.InternalTexture = InternalTexture;
  30192. })(BABYLON || (BABYLON = {}));
  30193. //# sourceMappingURL=babylon.internalTexture.js.map
  30194. var BABYLON;
  30195. (function (BABYLON) {
  30196. var BaseTexture = /** @class */ (function () {
  30197. function BaseTexture(scene) {
  30198. this._hasAlpha = false;
  30199. this.getAlphaFromRGB = false;
  30200. this.level = 1;
  30201. this.coordinatesIndex = 0;
  30202. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30203. /**
  30204. * | Value | Type | Description |
  30205. * | ----- | ------------------ | ----------- |
  30206. * | 0 | CLAMP_ADDRESSMODE | |
  30207. * | 1 | WRAP_ADDRESSMODE | |
  30208. * | 2 | MIRROR_ADDRESSMODE | |
  30209. */
  30210. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30211. /**
  30212. * | Value | Type | Description |
  30213. * | ----- | ------------------ | ----------- |
  30214. * | 0 | CLAMP_ADDRESSMODE | |
  30215. * | 1 | WRAP_ADDRESSMODE | |
  30216. * | 2 | MIRROR_ADDRESSMODE | |
  30217. */
  30218. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30219. /**
  30220. * | Value | Type | Description |
  30221. * | ----- | ------------------ | ----------- |
  30222. * | 0 | CLAMP_ADDRESSMODE | |
  30223. * | 1 | WRAP_ADDRESSMODE | |
  30224. * | 2 | MIRROR_ADDRESSMODE | |
  30225. */
  30226. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30227. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30228. this.isCube = false;
  30229. this.is3D = false;
  30230. this.gammaSpace = true;
  30231. this.invertZ = false;
  30232. this.lodLevelInAlpha = false;
  30233. this.isRenderTarget = false;
  30234. this.animations = new Array();
  30235. /**
  30236. * An event triggered when the texture is disposed.
  30237. */
  30238. this.onDisposeObservable = new BABYLON.Observable();
  30239. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30240. this._cachedSize = BABYLON.Size.Zero();
  30241. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30242. if (this._scene) {
  30243. this._scene.textures.push(this);
  30244. }
  30245. this._uid = null;
  30246. }
  30247. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30248. get: function () {
  30249. return this._hasAlpha;
  30250. },
  30251. set: function (value) {
  30252. if (this._hasAlpha === value) {
  30253. return;
  30254. }
  30255. this._hasAlpha = value;
  30256. if (this._scene) {
  30257. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30258. }
  30259. },
  30260. enumerable: true,
  30261. configurable: true
  30262. });
  30263. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30264. get: function () {
  30265. return this._coordinatesMode;
  30266. },
  30267. /**
  30268. * How a texture is mapped.
  30269. *
  30270. * | Value | Type | Description |
  30271. * | ----- | ----------------------------------- | ----------- |
  30272. * | 0 | EXPLICIT_MODE | |
  30273. * | 1 | SPHERICAL_MODE | |
  30274. * | 2 | PLANAR_MODE | |
  30275. * | 3 | CUBIC_MODE | |
  30276. * | 4 | PROJECTION_MODE | |
  30277. * | 5 | SKYBOX_MODE | |
  30278. * | 6 | INVCUBIC_MODE | |
  30279. * | 7 | EQUIRECTANGULAR_MODE | |
  30280. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30281. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30282. */
  30283. set: function (value) {
  30284. if (this._coordinatesMode === value) {
  30285. return;
  30286. }
  30287. this._coordinatesMode = value;
  30288. if (this._scene) {
  30289. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30290. }
  30291. },
  30292. enumerable: true,
  30293. configurable: true
  30294. });
  30295. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30296. /**
  30297. * Gets whether or not the texture contains RGBD data.
  30298. */
  30299. get: function () {
  30300. return this._texture != null && this._texture._isRGBD;
  30301. },
  30302. enumerable: true,
  30303. configurable: true
  30304. });
  30305. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30306. get: function () {
  30307. if (this._texture)
  30308. return this._texture._lodGenerationOffset;
  30309. return 0.0;
  30310. },
  30311. set: function (value) {
  30312. if (this._texture)
  30313. this._texture._lodGenerationOffset = value;
  30314. },
  30315. enumerable: true,
  30316. configurable: true
  30317. });
  30318. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30319. get: function () {
  30320. if (this._texture)
  30321. return this._texture._lodGenerationScale;
  30322. return 0.0;
  30323. },
  30324. set: function (value) {
  30325. if (this._texture)
  30326. this._texture._lodGenerationScale = value;
  30327. },
  30328. enumerable: true,
  30329. configurable: true
  30330. });
  30331. Object.defineProperty(BaseTexture.prototype, "uid", {
  30332. get: function () {
  30333. if (!this._uid) {
  30334. this._uid = BABYLON.Tools.RandomId();
  30335. }
  30336. return this._uid;
  30337. },
  30338. enumerable: true,
  30339. configurable: true
  30340. });
  30341. BaseTexture.prototype.toString = function () {
  30342. return this.name;
  30343. };
  30344. BaseTexture.prototype.getClassName = function () {
  30345. return "BaseTexture";
  30346. };
  30347. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30348. set: function (callback) {
  30349. if (this._onDisposeObserver) {
  30350. this.onDisposeObservable.remove(this._onDisposeObserver);
  30351. }
  30352. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30353. },
  30354. enumerable: true,
  30355. configurable: true
  30356. });
  30357. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30358. get: function () {
  30359. return true;
  30360. },
  30361. enumerable: true,
  30362. configurable: true
  30363. });
  30364. BaseTexture.prototype.getScene = function () {
  30365. return this._scene;
  30366. };
  30367. BaseTexture.prototype.getTextureMatrix = function () {
  30368. return BABYLON.Matrix.IdentityReadOnly;
  30369. };
  30370. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30371. return BABYLON.Matrix.IdentityReadOnly;
  30372. };
  30373. BaseTexture.prototype.getInternalTexture = function () {
  30374. return this._texture;
  30375. };
  30376. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30377. return !this.isBlocking || this.isReady();
  30378. };
  30379. BaseTexture.prototype.isReady = function () {
  30380. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30381. this.delayLoad();
  30382. return false;
  30383. }
  30384. if (this._texture) {
  30385. return this._texture.isReady;
  30386. }
  30387. return false;
  30388. };
  30389. BaseTexture.prototype.getSize = function () {
  30390. if (this._texture) {
  30391. if (this._texture.width) {
  30392. this._cachedSize.width = this._texture.width;
  30393. this._cachedSize.height = this._texture.height;
  30394. return this._cachedSize;
  30395. }
  30396. if (this._texture._size) {
  30397. this._cachedSize.width = this._texture._size;
  30398. this._cachedSize.height = this._texture._size;
  30399. return this._cachedSize;
  30400. }
  30401. }
  30402. return this._cachedSize;
  30403. };
  30404. BaseTexture.prototype.getBaseSize = function () {
  30405. if (!this.isReady() || !this._texture)
  30406. return BABYLON.Size.Zero();
  30407. if (this._texture._size) {
  30408. return new BABYLON.Size(this._texture._size, this._texture._size);
  30409. }
  30410. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30411. };
  30412. BaseTexture.prototype.scale = function (ratio) {
  30413. };
  30414. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30415. get: function () {
  30416. return false;
  30417. },
  30418. enumerable: true,
  30419. configurable: true
  30420. });
  30421. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30422. if (!this._scene) {
  30423. return null;
  30424. }
  30425. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30426. for (var index = 0; index < texturesCache.length; index++) {
  30427. var texturesCacheEntry = texturesCache[index];
  30428. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30429. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30430. texturesCacheEntry.incrementReferences();
  30431. return texturesCacheEntry;
  30432. }
  30433. }
  30434. }
  30435. return null;
  30436. };
  30437. BaseTexture.prototype._rebuild = function () {
  30438. };
  30439. BaseTexture.prototype.delayLoad = function () {
  30440. };
  30441. BaseTexture.prototype.clone = function () {
  30442. return null;
  30443. };
  30444. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30445. get: function () {
  30446. if (!this._texture) {
  30447. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30448. }
  30449. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30450. },
  30451. enumerable: true,
  30452. configurable: true
  30453. });
  30454. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30455. get: function () {
  30456. if (!this._texture) {
  30457. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30458. }
  30459. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30460. },
  30461. enumerable: true,
  30462. configurable: true
  30463. });
  30464. /**
  30465. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30466. * This will returns an RGBA array buffer containing either in values (0-255) or
  30467. * float values (0-1) depending of the underlying buffer type.
  30468. * @param faceIndex The face of the texture to read (in case of cube texture)
  30469. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30470. * @returns The Array buffer containing the pixels data.
  30471. */
  30472. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30473. if (faceIndex === void 0) { faceIndex = 0; }
  30474. if (level === void 0) { level = 0; }
  30475. if (!this._texture) {
  30476. return null;
  30477. }
  30478. var size = this.getSize();
  30479. var width = size.width;
  30480. var height = size.height;
  30481. var scene = this.getScene();
  30482. if (!scene) {
  30483. return null;
  30484. }
  30485. var engine = scene.getEngine();
  30486. if (level != 0) {
  30487. width = width / Math.pow(2, level);
  30488. height = height / Math.pow(2, level);
  30489. width = Math.round(width);
  30490. height = Math.round(height);
  30491. }
  30492. if (this._texture.isCube) {
  30493. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30494. }
  30495. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30496. };
  30497. BaseTexture.prototype.releaseInternalTexture = function () {
  30498. if (this._texture) {
  30499. this._texture.dispose();
  30500. this._texture = null;
  30501. }
  30502. };
  30503. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30504. get: function () {
  30505. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30506. return null;
  30507. }
  30508. if (!this._texture._sphericalPolynomial) {
  30509. this._texture._sphericalPolynomial =
  30510. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30511. }
  30512. return this._texture._sphericalPolynomial;
  30513. },
  30514. set: function (value) {
  30515. if (this._texture) {
  30516. this._texture._sphericalPolynomial = value;
  30517. }
  30518. },
  30519. enumerable: true,
  30520. configurable: true
  30521. });
  30522. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30523. get: function () {
  30524. if (this._texture) {
  30525. return this._texture._lodTextureHigh;
  30526. }
  30527. return null;
  30528. },
  30529. enumerable: true,
  30530. configurable: true
  30531. });
  30532. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30533. get: function () {
  30534. if (this._texture) {
  30535. return this._texture._lodTextureMid;
  30536. }
  30537. return null;
  30538. },
  30539. enumerable: true,
  30540. configurable: true
  30541. });
  30542. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30543. get: function () {
  30544. if (this._texture) {
  30545. return this._texture._lodTextureLow;
  30546. }
  30547. return null;
  30548. },
  30549. enumerable: true,
  30550. configurable: true
  30551. });
  30552. BaseTexture.prototype.dispose = function () {
  30553. if (!this._scene) {
  30554. return;
  30555. }
  30556. // Animations
  30557. this._scene.stopAnimation(this);
  30558. // Remove from scene
  30559. this._scene._removePendingData(this);
  30560. var index = this._scene.textures.indexOf(this);
  30561. if (index >= 0) {
  30562. this._scene.textures.splice(index, 1);
  30563. }
  30564. if (this._texture === undefined) {
  30565. return;
  30566. }
  30567. // Release
  30568. this.releaseInternalTexture();
  30569. // Callback
  30570. this.onDisposeObservable.notifyObservers(this);
  30571. this.onDisposeObservable.clear();
  30572. };
  30573. BaseTexture.prototype.serialize = function () {
  30574. if (!this.name) {
  30575. return null;
  30576. }
  30577. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30578. // Animations
  30579. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30580. return serializationObject;
  30581. };
  30582. BaseTexture.WhenAllReady = function (textures, callback) {
  30583. var numRemaining = textures.length;
  30584. if (numRemaining === 0) {
  30585. callback();
  30586. return;
  30587. }
  30588. var _loop_1 = function () {
  30589. texture = textures[i];
  30590. if (texture.isReady()) {
  30591. if (--numRemaining === 0) {
  30592. callback();
  30593. }
  30594. }
  30595. else {
  30596. onLoadObservable = texture.onLoadObservable;
  30597. var onLoadCallback_1 = function () {
  30598. onLoadObservable.removeCallback(onLoadCallback_1);
  30599. if (--numRemaining === 0) {
  30600. callback();
  30601. }
  30602. };
  30603. onLoadObservable.add(onLoadCallback_1);
  30604. }
  30605. };
  30606. var texture, onLoadObservable;
  30607. for (var i = 0; i < textures.length; i++) {
  30608. _loop_1();
  30609. }
  30610. };
  30611. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30612. __decorate([
  30613. BABYLON.serialize()
  30614. ], BaseTexture.prototype, "name", void 0);
  30615. __decorate([
  30616. BABYLON.serialize("hasAlpha")
  30617. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30618. __decorate([
  30619. BABYLON.serialize()
  30620. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30621. __decorate([
  30622. BABYLON.serialize()
  30623. ], BaseTexture.prototype, "level", void 0);
  30624. __decorate([
  30625. BABYLON.serialize()
  30626. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30627. __decorate([
  30628. BABYLON.serialize("coordinatesMode")
  30629. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30630. __decorate([
  30631. BABYLON.serialize()
  30632. ], BaseTexture.prototype, "wrapU", void 0);
  30633. __decorate([
  30634. BABYLON.serialize()
  30635. ], BaseTexture.prototype, "wrapV", void 0);
  30636. __decorate([
  30637. BABYLON.serialize()
  30638. ], BaseTexture.prototype, "wrapR", void 0);
  30639. __decorate([
  30640. BABYLON.serialize()
  30641. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30642. __decorate([
  30643. BABYLON.serialize()
  30644. ], BaseTexture.prototype, "isCube", void 0);
  30645. __decorate([
  30646. BABYLON.serialize()
  30647. ], BaseTexture.prototype, "is3D", void 0);
  30648. __decorate([
  30649. BABYLON.serialize()
  30650. ], BaseTexture.prototype, "gammaSpace", void 0);
  30651. __decorate([
  30652. BABYLON.serialize()
  30653. ], BaseTexture.prototype, "invertZ", void 0);
  30654. __decorate([
  30655. BABYLON.serialize()
  30656. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30657. __decorate([
  30658. BABYLON.serialize()
  30659. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30660. __decorate([
  30661. BABYLON.serialize()
  30662. ], BaseTexture.prototype, "lodGenerationScale", null);
  30663. __decorate([
  30664. BABYLON.serialize()
  30665. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30666. return BaseTexture;
  30667. }());
  30668. BABYLON.BaseTexture = BaseTexture;
  30669. })(BABYLON || (BABYLON = {}));
  30670. //# sourceMappingURL=babylon.baseTexture.js.map
  30671. var BABYLON;
  30672. (function (BABYLON) {
  30673. var Texture = /** @class */ (function (_super) {
  30674. __extends(Texture, _super);
  30675. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30676. if (noMipmap === void 0) { noMipmap = false; }
  30677. if (invertY === void 0) { invertY = true; }
  30678. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30679. if (onLoad === void 0) { onLoad = null; }
  30680. if (onError === void 0) { onError = null; }
  30681. if (buffer === void 0) { buffer = null; }
  30682. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30683. var _this = _super.call(this, scene) || this;
  30684. _this.uOffset = 0;
  30685. _this.vOffset = 0;
  30686. _this.uScale = 1.0;
  30687. _this.vScale = 1.0;
  30688. _this.uAng = 0;
  30689. _this.vAng = 0;
  30690. _this.wAng = 0;
  30691. /**
  30692. * Defines the center of rotation (U)
  30693. */
  30694. _this.uRotationCenter = 0.5;
  30695. /**
  30696. * Defines the center of rotation (V)
  30697. */
  30698. _this.vRotationCenter = 0.5;
  30699. /**
  30700. * Defines the center of rotation (W)
  30701. */
  30702. _this.wRotationCenter = 0.5;
  30703. _this._isBlocking = true;
  30704. _this.name = url || "";
  30705. _this.url = url;
  30706. _this._noMipmap = noMipmap;
  30707. _this._invertY = invertY;
  30708. _this._samplingMode = samplingMode;
  30709. _this._buffer = buffer;
  30710. _this._deleteBuffer = deleteBuffer;
  30711. if (format) {
  30712. _this._format = format;
  30713. }
  30714. scene = _this.getScene();
  30715. if (!scene) {
  30716. return _this;
  30717. }
  30718. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30719. var load = function () {
  30720. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30721. _this.onLoadObservable.notifyObservers(_this);
  30722. }
  30723. if (onLoad) {
  30724. onLoad();
  30725. }
  30726. if (!_this.isBlocking && scene) {
  30727. scene.resetCachedMaterial();
  30728. }
  30729. };
  30730. if (!_this.url) {
  30731. _this._delayedOnLoad = load;
  30732. _this._delayedOnError = onError;
  30733. return _this;
  30734. }
  30735. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30736. if (!_this._texture) {
  30737. if (!scene.useDelayedTextureLoading) {
  30738. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30739. if (deleteBuffer) {
  30740. delete _this._buffer;
  30741. }
  30742. }
  30743. else {
  30744. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30745. _this._delayedOnLoad = load;
  30746. _this._delayedOnError = onError;
  30747. }
  30748. }
  30749. else {
  30750. if (_this._texture.isReady) {
  30751. BABYLON.Tools.SetImmediate(function () { return load(); });
  30752. }
  30753. else {
  30754. _this._texture.onLoadedObservable.add(load);
  30755. }
  30756. }
  30757. return _this;
  30758. }
  30759. Object.defineProperty(Texture.prototype, "noMipmap", {
  30760. get: function () {
  30761. return this._noMipmap;
  30762. },
  30763. enumerable: true,
  30764. configurable: true
  30765. });
  30766. Object.defineProperty(Texture.prototype, "isBlocking", {
  30767. get: function () {
  30768. return this._isBlocking;
  30769. },
  30770. set: function (value) {
  30771. this._isBlocking = value;
  30772. },
  30773. enumerable: true,
  30774. configurable: true
  30775. });
  30776. Object.defineProperty(Texture.prototype, "samplingMode", {
  30777. get: function () {
  30778. return this._samplingMode;
  30779. },
  30780. enumerable: true,
  30781. configurable: true
  30782. });
  30783. /**
  30784. * Update the url (and optional buffer) of this texture if url was null during construction.
  30785. * @param url the url of the texture
  30786. * @param buffer the buffer of the texture (defaults to null)
  30787. */
  30788. Texture.prototype.updateURL = function (url, buffer) {
  30789. if (buffer === void 0) { buffer = null; }
  30790. if (this.url) {
  30791. throw new Error("URL is already set");
  30792. }
  30793. this.url = url;
  30794. this._buffer = buffer;
  30795. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30796. this.delayLoad();
  30797. };
  30798. Texture.prototype.delayLoad = function () {
  30799. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30800. return;
  30801. }
  30802. var scene = this.getScene();
  30803. if (!scene) {
  30804. return;
  30805. }
  30806. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30807. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30808. if (!this._texture) {
  30809. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30810. if (this._deleteBuffer) {
  30811. delete this._buffer;
  30812. }
  30813. }
  30814. else {
  30815. if (this._delayedOnLoad) {
  30816. if (this._texture.isReady) {
  30817. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30818. }
  30819. else {
  30820. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30821. }
  30822. }
  30823. }
  30824. this._delayedOnLoad = null;
  30825. this._delayedOnError = null;
  30826. };
  30827. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30828. if (!this._texture) {
  30829. return;
  30830. }
  30831. var scene = this.getScene();
  30832. if (!scene) {
  30833. return;
  30834. }
  30835. this._samplingMode = samplingMode;
  30836. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30837. };
  30838. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30839. x *= this.uScale;
  30840. y *= this.vScale;
  30841. x -= this.uRotationCenter * this.uScale;
  30842. y -= this.vRotationCenter * this.vScale;
  30843. z -= this.wRotationCenter;
  30844. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30845. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30846. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30847. t.z += this.wRotationCenter;
  30848. };
  30849. Texture.prototype.getTextureMatrix = function () {
  30850. var _this = this;
  30851. if (this.uOffset === this._cachedUOffset &&
  30852. this.vOffset === this._cachedVOffset &&
  30853. this.uScale === this._cachedUScale &&
  30854. this.vScale === this._cachedVScale &&
  30855. this.uAng === this._cachedUAng &&
  30856. this.vAng === this._cachedVAng &&
  30857. this.wAng === this._cachedWAng) {
  30858. return this._cachedTextureMatrix;
  30859. }
  30860. this._cachedUOffset = this.uOffset;
  30861. this._cachedVOffset = this.vOffset;
  30862. this._cachedUScale = this.uScale;
  30863. this._cachedVScale = this.vScale;
  30864. this._cachedUAng = this.uAng;
  30865. this._cachedVAng = this.vAng;
  30866. this._cachedWAng = this.wAng;
  30867. if (!this._cachedTextureMatrix) {
  30868. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30869. this._rowGenerationMatrix = new BABYLON.Matrix();
  30870. this._t0 = BABYLON.Vector3.Zero();
  30871. this._t1 = BABYLON.Vector3.Zero();
  30872. this._t2 = BABYLON.Vector3.Zero();
  30873. }
  30874. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30875. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30876. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30877. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30878. this._t1.subtractInPlace(this._t0);
  30879. this._t2.subtractInPlace(this._t0);
  30880. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30881. this._cachedTextureMatrix.m[0] = this._t1.x;
  30882. this._cachedTextureMatrix.m[1] = this._t1.y;
  30883. this._cachedTextureMatrix.m[2] = this._t1.z;
  30884. this._cachedTextureMatrix.m[4] = this._t2.x;
  30885. this._cachedTextureMatrix.m[5] = this._t2.y;
  30886. this._cachedTextureMatrix.m[6] = this._t2.z;
  30887. this._cachedTextureMatrix.m[8] = this._t0.x;
  30888. this._cachedTextureMatrix.m[9] = this._t0.y;
  30889. this._cachedTextureMatrix.m[10] = this._t0.z;
  30890. var scene = this.getScene();
  30891. if (!scene) {
  30892. return this._cachedTextureMatrix;
  30893. }
  30894. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30895. return mat.hasTexture(_this);
  30896. });
  30897. return this._cachedTextureMatrix;
  30898. };
  30899. Texture.prototype.getReflectionTextureMatrix = function () {
  30900. var _this = this;
  30901. var scene = this.getScene();
  30902. if (!scene) {
  30903. return this._cachedTextureMatrix;
  30904. }
  30905. if (this.uOffset === this._cachedUOffset &&
  30906. this.vOffset === this._cachedVOffset &&
  30907. this.uScale === this._cachedUScale &&
  30908. this.vScale === this._cachedVScale &&
  30909. this.coordinatesMode === this._cachedCoordinatesMode) {
  30910. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30911. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30912. return this._cachedTextureMatrix;
  30913. }
  30914. }
  30915. else {
  30916. return this._cachedTextureMatrix;
  30917. }
  30918. }
  30919. if (!this._cachedTextureMatrix) {
  30920. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30921. }
  30922. if (!this._projectionModeMatrix) {
  30923. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30924. }
  30925. this._cachedUOffset = this.uOffset;
  30926. this._cachedVOffset = this.vOffset;
  30927. this._cachedUScale = this.uScale;
  30928. this._cachedVScale = this.vScale;
  30929. this._cachedCoordinatesMode = this.coordinatesMode;
  30930. switch (this.coordinatesMode) {
  30931. case Texture.PLANAR_MODE:
  30932. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30933. this._cachedTextureMatrix[0] = this.uScale;
  30934. this._cachedTextureMatrix[5] = this.vScale;
  30935. this._cachedTextureMatrix[12] = this.uOffset;
  30936. this._cachedTextureMatrix[13] = this.vOffset;
  30937. break;
  30938. case Texture.PROJECTION_MODE:
  30939. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30940. this._projectionModeMatrix.m[0] = 0.5;
  30941. this._projectionModeMatrix.m[5] = -0.5;
  30942. this._projectionModeMatrix.m[10] = 0.0;
  30943. this._projectionModeMatrix.m[12] = 0.5;
  30944. this._projectionModeMatrix.m[13] = 0.5;
  30945. this._projectionModeMatrix.m[14] = 1.0;
  30946. this._projectionModeMatrix.m[15] = 1.0;
  30947. var projectionMatrix = scene.getProjectionMatrix();
  30948. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30949. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30950. break;
  30951. default:
  30952. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30953. break;
  30954. }
  30955. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30956. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30957. });
  30958. return this._cachedTextureMatrix;
  30959. };
  30960. Texture.prototype.clone = function () {
  30961. var _this = this;
  30962. return BABYLON.SerializationHelper.Clone(function () {
  30963. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30964. }, this);
  30965. };
  30966. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30967. get: function () {
  30968. if (!this._onLoadObservable) {
  30969. this._onLoadObservable = new BABYLON.Observable();
  30970. }
  30971. return this._onLoadObservable;
  30972. },
  30973. enumerable: true,
  30974. configurable: true
  30975. });
  30976. Texture.prototype.serialize = function () {
  30977. var serializationObject = _super.prototype.serialize.call(this);
  30978. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30979. serializationObject.base64String = this._buffer;
  30980. serializationObject.name = serializationObject.name.replace("data:", "");
  30981. }
  30982. serializationObject.invertY = this._invertY;
  30983. serializationObject.samplingMode = this.samplingMode;
  30984. return serializationObject;
  30985. };
  30986. Texture.prototype.getClassName = function () {
  30987. return "Texture";
  30988. };
  30989. Texture.prototype.dispose = function () {
  30990. _super.prototype.dispose.call(this);
  30991. if (this._onLoadObservable) {
  30992. this._onLoadObservable.clear();
  30993. this._onLoadObservable = null;
  30994. }
  30995. this._delayedOnLoad = null;
  30996. this._delayedOnError = null;
  30997. };
  30998. // Statics
  30999. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31000. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31001. if (onLoad === void 0) { onLoad = null; }
  31002. if (onError === void 0) { onError = null; }
  31003. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31004. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31005. };
  31006. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31007. if (parsedTexture.customType) {
  31008. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31009. // Update Sampling Mode
  31010. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31011. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31012. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31013. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31014. }
  31015. }
  31016. return parsedCustomTexture;
  31017. }
  31018. if (parsedTexture.isCube) {
  31019. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31020. }
  31021. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31022. return null;
  31023. }
  31024. var texture = BABYLON.SerializationHelper.Parse(function () {
  31025. var generateMipMaps = true;
  31026. if (parsedTexture.noMipmap) {
  31027. generateMipMaps = false;
  31028. }
  31029. if (parsedTexture.mirrorPlane) {
  31030. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31031. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31032. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31033. return mirrorTexture;
  31034. }
  31035. else if (parsedTexture.isRenderTarget) {
  31036. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31037. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31038. return renderTargetTexture;
  31039. }
  31040. else {
  31041. var texture;
  31042. if (parsedTexture.base64String) {
  31043. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31044. }
  31045. else {
  31046. var url = rootUrl + parsedTexture.name;
  31047. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31048. url = parsedTexture.url;
  31049. }
  31050. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31051. }
  31052. return texture;
  31053. }
  31054. }, parsedTexture, scene);
  31055. // Update Sampling Mode
  31056. if (parsedTexture.samplingMode) {
  31057. var sampling = parsedTexture.samplingMode;
  31058. if (texture._samplingMode !== sampling) {
  31059. texture.updateSamplingMode(sampling);
  31060. }
  31061. }
  31062. // Animations
  31063. if (parsedTexture.animations) {
  31064. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31065. var parsedAnimation = parsedTexture.animations[animationIndex];
  31066. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31067. }
  31068. }
  31069. return texture;
  31070. };
  31071. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31072. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31073. if (noMipmap === void 0) { noMipmap = false; }
  31074. if (invertY === void 0) { invertY = true; }
  31075. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31076. if (onLoad === void 0) { onLoad = null; }
  31077. if (onError === void 0) { onError = null; }
  31078. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31079. if (name.substr(0, 5) !== "data:") {
  31080. name = "data:" + name;
  31081. }
  31082. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31083. };
  31084. // Constants
  31085. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31086. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31087. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31088. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31089. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31090. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31091. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31092. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31093. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31094. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31095. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31096. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31097. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31098. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31099. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31100. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31101. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31102. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31103. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31104. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31105. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31106. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31107. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31108. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31109. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31110. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31111. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31112. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31113. /**
  31114. * 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
  31115. */
  31116. Texture.UseSerializedUrlIfAny = false;
  31117. __decorate([
  31118. BABYLON.serialize()
  31119. ], Texture.prototype, "url", void 0);
  31120. __decorate([
  31121. BABYLON.serialize()
  31122. ], Texture.prototype, "uOffset", void 0);
  31123. __decorate([
  31124. BABYLON.serialize()
  31125. ], Texture.prototype, "vOffset", void 0);
  31126. __decorate([
  31127. BABYLON.serialize()
  31128. ], Texture.prototype, "uScale", void 0);
  31129. __decorate([
  31130. BABYLON.serialize()
  31131. ], Texture.prototype, "vScale", void 0);
  31132. __decorate([
  31133. BABYLON.serialize()
  31134. ], Texture.prototype, "uAng", void 0);
  31135. __decorate([
  31136. BABYLON.serialize()
  31137. ], Texture.prototype, "vAng", void 0);
  31138. __decorate([
  31139. BABYLON.serialize()
  31140. ], Texture.prototype, "wAng", void 0);
  31141. __decorate([
  31142. BABYLON.serialize()
  31143. ], Texture.prototype, "uRotationCenter", void 0);
  31144. __decorate([
  31145. BABYLON.serialize()
  31146. ], Texture.prototype, "vRotationCenter", void 0);
  31147. __decorate([
  31148. BABYLON.serialize()
  31149. ], Texture.prototype, "wRotationCenter", void 0);
  31150. __decorate([
  31151. BABYLON.serialize()
  31152. ], Texture.prototype, "isBlocking", null);
  31153. return Texture;
  31154. }(BABYLON.BaseTexture));
  31155. BABYLON.Texture = Texture;
  31156. })(BABYLON || (BABYLON = {}));
  31157. //# sourceMappingURL=babylon.texture.js.map
  31158. var BABYLON;
  31159. (function (BABYLON) {
  31160. /**
  31161. * @hidden
  31162. **/
  31163. var _InstancesBatch = /** @class */ (function () {
  31164. function _InstancesBatch() {
  31165. this.mustReturn = false;
  31166. this.visibleInstances = new Array();
  31167. this.renderSelf = new Array();
  31168. }
  31169. return _InstancesBatch;
  31170. }());
  31171. BABYLON._InstancesBatch = _InstancesBatch;
  31172. var Mesh = /** @class */ (function (_super) {
  31173. __extends(Mesh, _super);
  31174. /**
  31175. * @constructor
  31176. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31177. * @param {Scene} scene The scene to add this mesh to.
  31178. * @param {Node} parent The parent of this mesh, if it has one
  31179. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31180. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31181. * When false, achieved by calling a clone(), also passing False.
  31182. * This will make creation of children, recursive.
  31183. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31184. */
  31185. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31186. if (scene === void 0) { scene = null; }
  31187. if (parent === void 0) { parent = null; }
  31188. if (source === void 0) { source = null; }
  31189. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31190. var _this = _super.call(this, name, scene) || this;
  31191. // Events
  31192. /**
  31193. * An event triggered before rendering the mesh
  31194. */
  31195. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31196. /**
  31197. * An event triggered after rendering the mesh
  31198. */
  31199. _this.onAfterRenderObservable = new BABYLON.Observable();
  31200. /**
  31201. * An event triggered before drawing the mesh
  31202. */
  31203. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31204. // Members
  31205. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31206. _this.instances = new Array();
  31207. _this._LODLevels = new Array();
  31208. _this._visibleInstances = {};
  31209. _this._renderIdForInstances = new Array();
  31210. _this._batchCache = new _InstancesBatch();
  31211. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31212. // Use by builder only to know what orientation were the mesh build in.
  31213. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31214. _this.overrideMaterialSideOrientation = null;
  31215. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31216. // Will be used to save a source mesh reference, If any
  31217. _this._source = null;
  31218. scene = _this.getScene();
  31219. if (source) {
  31220. // Geometry
  31221. if (source._geometry) {
  31222. source._geometry.applyToMesh(_this);
  31223. }
  31224. // Deep copy
  31225. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31226. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31227. // Source mesh
  31228. _this._source = source;
  31229. // Metadata
  31230. if (source.metadata && source.metadata.clone) {
  31231. _this.metadata = source.metadata.clone();
  31232. }
  31233. else {
  31234. _this.metadata = source.metadata;
  31235. }
  31236. // Tags
  31237. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31238. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31239. }
  31240. // Parent
  31241. _this.parent = source.parent;
  31242. // Pivot
  31243. _this.setPivotMatrix(source.getPivotMatrix());
  31244. _this.id = name + "." + source.id;
  31245. // Material
  31246. _this.material = source.material;
  31247. var index;
  31248. if (!doNotCloneChildren) {
  31249. // Children
  31250. var directDescendants = source.getDescendants(true);
  31251. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31252. var child = directDescendants[index_1];
  31253. if (child.clone) {
  31254. child.clone(name + "." + child.name, _this);
  31255. }
  31256. }
  31257. }
  31258. // Physics clone
  31259. var physicsEngine = _this.getScene().getPhysicsEngine();
  31260. if (clonePhysicsImpostor && physicsEngine) {
  31261. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31262. if (impostor) {
  31263. _this.physicsImpostor = impostor.clone(_this);
  31264. }
  31265. }
  31266. // Particles
  31267. for (index = 0; index < scene.particleSystems.length; index++) {
  31268. var system = scene.particleSystems[index];
  31269. if (system.emitter === source) {
  31270. system.clone(system.name, _this);
  31271. }
  31272. }
  31273. _this.refreshBoundingInfo();
  31274. _this.computeWorldMatrix(true);
  31275. }
  31276. // Parent
  31277. if (parent !== null) {
  31278. _this.parent = parent;
  31279. }
  31280. return _this;
  31281. }
  31282. Object.defineProperty(Mesh, "FRONTSIDE", {
  31283. /**
  31284. * Mesh side orientation : usually the external or front surface
  31285. */
  31286. get: function () {
  31287. return Mesh._FRONTSIDE;
  31288. },
  31289. enumerable: true,
  31290. configurable: true
  31291. });
  31292. Object.defineProperty(Mesh, "BACKSIDE", {
  31293. /**
  31294. * Mesh side orientation : usually the internal or back surface
  31295. */
  31296. get: function () {
  31297. return Mesh._BACKSIDE;
  31298. },
  31299. enumerable: true,
  31300. configurable: true
  31301. });
  31302. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31303. /**
  31304. * Mesh side orientation : both internal and external or front and back surfaces
  31305. */
  31306. get: function () {
  31307. return Mesh._DOUBLESIDE;
  31308. },
  31309. enumerable: true,
  31310. configurable: true
  31311. });
  31312. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31313. /**
  31314. * Mesh side orientation : by default, `FRONTSIDE`
  31315. */
  31316. get: function () {
  31317. return Mesh._DEFAULTSIDE;
  31318. },
  31319. enumerable: true,
  31320. configurable: true
  31321. });
  31322. Object.defineProperty(Mesh, "NO_CAP", {
  31323. /**
  31324. * Mesh cap setting : no cap
  31325. */
  31326. get: function () {
  31327. return Mesh._NO_CAP;
  31328. },
  31329. enumerable: true,
  31330. configurable: true
  31331. });
  31332. Object.defineProperty(Mesh, "CAP_START", {
  31333. /**
  31334. * Mesh cap setting : one cap at the beginning of the mesh
  31335. */
  31336. get: function () {
  31337. return Mesh._CAP_START;
  31338. },
  31339. enumerable: true,
  31340. configurable: true
  31341. });
  31342. Object.defineProperty(Mesh, "CAP_END", {
  31343. /**
  31344. * Mesh cap setting : one cap at the end of the mesh
  31345. */
  31346. get: function () {
  31347. return Mesh._CAP_END;
  31348. },
  31349. enumerable: true,
  31350. configurable: true
  31351. });
  31352. Object.defineProperty(Mesh, "CAP_ALL", {
  31353. /**
  31354. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31355. */
  31356. get: function () {
  31357. return Mesh._CAP_ALL;
  31358. },
  31359. enumerable: true,
  31360. configurable: true
  31361. });
  31362. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31363. set: function (callback) {
  31364. if (this._onBeforeDrawObserver) {
  31365. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31366. }
  31367. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31368. },
  31369. enumerable: true,
  31370. configurable: true
  31371. });
  31372. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31373. get: function () {
  31374. return this._morphTargetManager;
  31375. },
  31376. set: function (value) {
  31377. if (this._morphTargetManager === value) {
  31378. return;
  31379. }
  31380. this._morphTargetManager = value;
  31381. this._syncGeometryWithMorphTargetManager();
  31382. },
  31383. enumerable: true,
  31384. configurable: true
  31385. });
  31386. Object.defineProperty(Mesh.prototype, "source", {
  31387. get: function () {
  31388. return this._source;
  31389. },
  31390. enumerable: true,
  31391. configurable: true
  31392. });
  31393. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31394. get: function () {
  31395. return this._unIndexed;
  31396. },
  31397. set: function (value) {
  31398. if (this._unIndexed !== value) {
  31399. this._unIndexed = value;
  31400. this._markSubMeshesAsAttributesDirty();
  31401. }
  31402. },
  31403. enumerable: true,
  31404. configurable: true
  31405. });
  31406. // Methods
  31407. /**
  31408. * Returns the string "Mesh".
  31409. */
  31410. Mesh.prototype.getClassName = function () {
  31411. return "Mesh";
  31412. };
  31413. /**
  31414. * Returns a string.
  31415. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31416. */
  31417. Mesh.prototype.toString = function (fullDetails) {
  31418. var ret = _super.prototype.toString.call(this, fullDetails);
  31419. ret += ", n vertices: " + this.getTotalVertices();
  31420. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31421. if (this.animations) {
  31422. for (var i = 0; i < this.animations.length; i++) {
  31423. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31424. }
  31425. }
  31426. if (fullDetails) {
  31427. if (this._geometry) {
  31428. var ib = this.getIndices();
  31429. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31430. if (vb && ib) {
  31431. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31432. }
  31433. }
  31434. else {
  31435. ret += ", flat shading: UNKNOWN";
  31436. }
  31437. }
  31438. return ret;
  31439. };
  31440. Mesh.prototype._unBindEffect = function () {
  31441. _super.prototype._unBindEffect.call(this);
  31442. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31443. var instance = _a[_i];
  31444. instance._unBindEffect();
  31445. }
  31446. };
  31447. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31448. /**
  31449. * True if the mesh has some Levels Of Details (LOD).
  31450. * Returns a boolean.
  31451. */
  31452. get: function () {
  31453. return this._LODLevels.length > 0;
  31454. },
  31455. enumerable: true,
  31456. configurable: true
  31457. });
  31458. /**
  31459. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31460. * @returns an array of {BABYLON.MeshLODLevel}
  31461. */
  31462. Mesh.prototype.getLODLevels = function () {
  31463. return this._LODLevels;
  31464. };
  31465. Mesh.prototype._sortLODLevels = function () {
  31466. this._LODLevels.sort(function (a, b) {
  31467. if (a.distance < b.distance) {
  31468. return 1;
  31469. }
  31470. if (a.distance > b.distance) {
  31471. return -1;
  31472. }
  31473. return 0;
  31474. });
  31475. };
  31476. /**
  31477. * Add a mesh as LOD level triggered at the given distance.
  31478. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31479. * @param distance The distance from the center of the object to show this level
  31480. * @param mesh The mesh to be added as LOD level (can be null)
  31481. * @return This mesh (for chaining)
  31482. */
  31483. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31484. if (mesh && mesh._masterMesh) {
  31485. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31486. return this;
  31487. }
  31488. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31489. this._LODLevels.push(level);
  31490. if (mesh) {
  31491. mesh._masterMesh = this;
  31492. }
  31493. this._sortLODLevels();
  31494. return this;
  31495. };
  31496. /**
  31497. * Returns the LOD level mesh at the passed distance or null if not found.
  31498. * It is related to the method `addLODLevel(distance, mesh)`.
  31499. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31500. * Returns an object Mesh or `null`.
  31501. */
  31502. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31503. for (var index = 0; index < this._LODLevels.length; index++) {
  31504. var level = this._LODLevels[index];
  31505. if (level.distance === distance) {
  31506. return level.mesh;
  31507. }
  31508. }
  31509. return null;
  31510. };
  31511. /**
  31512. * Remove a mesh from the LOD array
  31513. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31514. * @param {Mesh} mesh The mesh to be removed.
  31515. * @return {Mesh} This mesh (for chaining)
  31516. */
  31517. Mesh.prototype.removeLODLevel = function (mesh) {
  31518. for (var index = 0; index < this._LODLevels.length; index++) {
  31519. if (this._LODLevels[index].mesh === mesh) {
  31520. this._LODLevels.splice(index, 1);
  31521. if (mesh) {
  31522. mesh._masterMesh = null;
  31523. }
  31524. }
  31525. }
  31526. this._sortLODLevels();
  31527. return this;
  31528. };
  31529. /**
  31530. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31531. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31532. */
  31533. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31534. if (!this._LODLevels || this._LODLevels.length === 0) {
  31535. return this;
  31536. }
  31537. var bSphere;
  31538. if (boundingSphere) {
  31539. bSphere = boundingSphere;
  31540. }
  31541. else {
  31542. var boundingInfo = this.getBoundingInfo();
  31543. bSphere = boundingInfo.boundingSphere;
  31544. }
  31545. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31546. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31547. if (this.onLODLevelSelection) {
  31548. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31549. }
  31550. return this;
  31551. }
  31552. for (var index = 0; index < this._LODLevels.length; index++) {
  31553. var level = this._LODLevels[index];
  31554. if (level.distance < distanceToCamera) {
  31555. if (level.mesh) {
  31556. level.mesh._preActivate();
  31557. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31558. }
  31559. if (this.onLODLevelSelection) {
  31560. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31561. }
  31562. return level.mesh;
  31563. }
  31564. }
  31565. if (this.onLODLevelSelection) {
  31566. this.onLODLevelSelection(distanceToCamera, this, this);
  31567. }
  31568. return this;
  31569. };
  31570. Object.defineProperty(Mesh.prototype, "geometry", {
  31571. /**
  31572. * Returns the mesh internal Geometry object.
  31573. */
  31574. get: function () {
  31575. return this._geometry;
  31576. },
  31577. enumerable: true,
  31578. configurable: true
  31579. });
  31580. /**
  31581. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31582. */
  31583. Mesh.prototype.getTotalVertices = function () {
  31584. if (this._geometry === null || this._geometry === undefined) {
  31585. return 0;
  31586. }
  31587. return this._geometry.getTotalVertices();
  31588. };
  31589. /**
  31590. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31591. * 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.
  31592. * You can force the copy with forceCopy === true
  31593. * Returns null if the mesh has no geometry or no vertex buffer.
  31594. * Possible `kind` values :
  31595. * - BABYLON.VertexBuffer.PositionKind
  31596. * - BABYLON.VertexBuffer.UVKind
  31597. * - BABYLON.VertexBuffer.UV2Kind
  31598. * - BABYLON.VertexBuffer.UV3Kind
  31599. * - BABYLON.VertexBuffer.UV4Kind
  31600. * - BABYLON.VertexBuffer.UV5Kind
  31601. * - BABYLON.VertexBuffer.UV6Kind
  31602. * - BABYLON.VertexBuffer.ColorKind
  31603. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31604. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31605. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31606. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31607. */
  31608. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31609. if (!this._geometry) {
  31610. return null;
  31611. }
  31612. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31613. };
  31614. /**
  31615. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31616. * Returns `null` if the mesh has no geometry.
  31617. * Possible `kind` values :
  31618. * - BABYLON.VertexBuffer.PositionKind
  31619. * - BABYLON.VertexBuffer.UVKind
  31620. * - BABYLON.VertexBuffer.UV2Kind
  31621. * - BABYLON.VertexBuffer.UV3Kind
  31622. * - BABYLON.VertexBuffer.UV4Kind
  31623. * - BABYLON.VertexBuffer.UV5Kind
  31624. * - BABYLON.VertexBuffer.UV6Kind
  31625. * - BABYLON.VertexBuffer.ColorKind
  31626. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31627. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31628. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31629. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31630. */
  31631. Mesh.prototype.getVertexBuffer = function (kind) {
  31632. if (!this._geometry) {
  31633. return null;
  31634. }
  31635. return this._geometry.getVertexBuffer(kind);
  31636. };
  31637. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31638. if (!this._geometry) {
  31639. if (this._delayInfo) {
  31640. return this._delayInfo.indexOf(kind) !== -1;
  31641. }
  31642. return false;
  31643. }
  31644. return this._geometry.isVerticesDataPresent(kind);
  31645. };
  31646. /**
  31647. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31648. * Possible `kind` values :
  31649. * - BABYLON.VertexBuffer.PositionKind
  31650. * - BABYLON.VertexBuffer.UVKind
  31651. * - BABYLON.VertexBuffer.UV2Kind
  31652. * - BABYLON.VertexBuffer.UV3Kind
  31653. * - BABYLON.VertexBuffer.UV4Kind
  31654. * - BABYLON.VertexBuffer.UV5Kind
  31655. * - BABYLON.VertexBuffer.UV6Kind
  31656. * - BABYLON.VertexBuffer.ColorKind
  31657. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31658. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31659. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31660. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31661. */
  31662. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31663. if (!this._geometry) {
  31664. if (this._delayInfo) {
  31665. return this._delayInfo.indexOf(kind) !== -1;
  31666. }
  31667. return false;
  31668. }
  31669. return this._geometry.isVertexBufferUpdatable(kind);
  31670. };
  31671. /**
  31672. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31673. * Possible `kind` values :
  31674. * - BABYLON.VertexBuffer.PositionKind
  31675. * - BABYLON.VertexBuffer.UVKind
  31676. * - BABYLON.VertexBuffer.UV2Kind
  31677. * - BABYLON.VertexBuffer.UV3Kind
  31678. * - BABYLON.VertexBuffer.UV4Kind
  31679. * - BABYLON.VertexBuffer.UV5Kind
  31680. * - BABYLON.VertexBuffer.UV6Kind
  31681. * - BABYLON.VertexBuffer.ColorKind
  31682. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31683. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31684. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31685. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31686. */
  31687. Mesh.prototype.getVerticesDataKinds = function () {
  31688. if (!this._geometry) {
  31689. var result = new Array();
  31690. if (this._delayInfo) {
  31691. this._delayInfo.forEach(function (kind, index, array) {
  31692. result.push(kind);
  31693. });
  31694. }
  31695. return result;
  31696. }
  31697. return this._geometry.getVerticesDataKinds();
  31698. };
  31699. /**
  31700. * Returns a positive integer : the total number of indices in this mesh geometry.
  31701. * Returns zero if the mesh has no geometry.
  31702. */
  31703. Mesh.prototype.getTotalIndices = function () {
  31704. if (!this._geometry) {
  31705. return 0;
  31706. }
  31707. return this._geometry.getTotalIndices();
  31708. };
  31709. /**
  31710. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31711. * 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.
  31712. * Returns an empty array if the mesh has no geometry.
  31713. */
  31714. Mesh.prototype.getIndices = function (copyWhenShared) {
  31715. if (!this._geometry) {
  31716. return [];
  31717. }
  31718. return this._geometry.getIndices(copyWhenShared);
  31719. };
  31720. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31721. get: function () {
  31722. return this._masterMesh !== null && this._masterMesh !== undefined;
  31723. },
  31724. enumerable: true,
  31725. configurable: true
  31726. });
  31727. /**
  31728. * Determine if the current mesh is ready to be rendered
  31729. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31730. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31731. * @returns true if all associated assets are ready (material, textures, shaders)
  31732. */
  31733. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31734. if (completeCheck === void 0) { completeCheck = false; }
  31735. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31736. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31737. return false;
  31738. }
  31739. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31740. return false;
  31741. }
  31742. if (!this.subMeshes || this.subMeshes.length === 0) {
  31743. return true;
  31744. }
  31745. if (!completeCheck) {
  31746. return true;
  31747. }
  31748. var engine = this.getEngine();
  31749. var scene = this.getScene();
  31750. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31751. this.computeWorldMatrix();
  31752. var mat = this.material || scene.defaultMaterial;
  31753. if (mat) {
  31754. if (mat.storeEffectOnSubMeshes) {
  31755. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31756. var subMesh = _a[_i];
  31757. var effectiveMaterial = subMesh.getMaterial();
  31758. if (effectiveMaterial) {
  31759. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31760. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31761. return false;
  31762. }
  31763. }
  31764. else {
  31765. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31766. return false;
  31767. }
  31768. }
  31769. }
  31770. }
  31771. }
  31772. else {
  31773. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31774. return false;
  31775. }
  31776. }
  31777. }
  31778. // Shadows
  31779. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31780. var light = _c[_b];
  31781. var generator = light.getShadowGenerator();
  31782. if (generator) {
  31783. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31784. var subMesh = _e[_d];
  31785. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31786. return false;
  31787. }
  31788. }
  31789. }
  31790. }
  31791. // LOD
  31792. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31793. var lod = _g[_f];
  31794. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31795. return false;
  31796. }
  31797. }
  31798. return true;
  31799. };
  31800. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31801. /**
  31802. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31803. * This property is pertinent only for updatable parametric shapes.
  31804. */
  31805. get: function () {
  31806. return this._areNormalsFrozen;
  31807. },
  31808. enumerable: true,
  31809. configurable: true
  31810. });
  31811. /**
  31812. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31813. * It has no effect at all on other shapes.
  31814. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31815. * Returns the Mesh.
  31816. */
  31817. Mesh.prototype.freezeNormals = function () {
  31818. this._areNormalsFrozen = true;
  31819. return this;
  31820. };
  31821. /**
  31822. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31823. * It has no effect at all on other shapes.
  31824. * It reactivates the mesh normals computation if it was previously frozen.
  31825. * Returns the Mesh.
  31826. */
  31827. Mesh.prototype.unfreezeNormals = function () {
  31828. this._areNormalsFrozen = false;
  31829. return this;
  31830. };
  31831. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31832. /**
  31833. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31834. */
  31835. set: function (count) {
  31836. this._overridenInstanceCount = count;
  31837. },
  31838. enumerable: true,
  31839. configurable: true
  31840. });
  31841. // Methods
  31842. Mesh.prototype._preActivate = function () {
  31843. var sceneRenderId = this.getScene().getRenderId();
  31844. if (this._preActivateId === sceneRenderId) {
  31845. return this;
  31846. }
  31847. this._preActivateId = sceneRenderId;
  31848. this._visibleInstances = null;
  31849. return this;
  31850. };
  31851. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31852. if (this._visibleInstances) {
  31853. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31854. }
  31855. return this;
  31856. };
  31857. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31858. if (!this._visibleInstances) {
  31859. this._visibleInstances = {};
  31860. this._visibleInstances.defaultRenderId = renderId;
  31861. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31862. }
  31863. if (!this._visibleInstances[renderId]) {
  31864. this._visibleInstances[renderId] = new Array();
  31865. }
  31866. this._visibleInstances[renderId].push(instance);
  31867. return this;
  31868. };
  31869. /**
  31870. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31871. * This means the mesh underlying bounding box and sphere are recomputed.
  31872. * Returns the Mesh.
  31873. */
  31874. Mesh.prototype.refreshBoundingInfo = function () {
  31875. return this._refreshBoundingInfo(false);
  31876. };
  31877. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31878. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31879. return this;
  31880. }
  31881. var data = this._getPositionData(applySkeleton);
  31882. if (data) {
  31883. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31884. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31885. }
  31886. if (this.subMeshes) {
  31887. for (var index = 0; index < this.subMeshes.length; index++) {
  31888. this.subMeshes[index].refreshBoundingInfo();
  31889. }
  31890. }
  31891. this._updateBoundingInfo();
  31892. return this;
  31893. };
  31894. Mesh.prototype._getPositionData = function (applySkeleton) {
  31895. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31896. if (data && applySkeleton && this.skeleton) {
  31897. data = BABYLON.Tools.Slice(data);
  31898. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31899. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31900. if (matricesWeightsData && matricesIndicesData) {
  31901. var needExtras = this.numBoneInfluencers > 4;
  31902. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31903. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31904. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31905. var tempVector = BABYLON.Tmp.Vector3[0];
  31906. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31907. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31908. var matWeightIdx = 0;
  31909. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31910. finalMatrix.reset();
  31911. var inf;
  31912. var weight;
  31913. for (inf = 0; inf < 4; inf++) {
  31914. weight = matricesWeightsData[matWeightIdx + inf];
  31915. if (weight > 0) {
  31916. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31917. finalMatrix.addToSelf(tempMatrix);
  31918. }
  31919. }
  31920. if (needExtras) {
  31921. for (inf = 0; inf < 4; inf++) {
  31922. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31923. if (weight > 0) {
  31924. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31925. finalMatrix.addToSelf(tempMatrix);
  31926. }
  31927. }
  31928. }
  31929. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31930. tempVector.toArray(data, index);
  31931. }
  31932. }
  31933. }
  31934. return data;
  31935. };
  31936. Mesh.prototype._createGlobalSubMesh = function (force) {
  31937. var totalVertices = this.getTotalVertices();
  31938. if (!totalVertices || !this.getIndices()) {
  31939. return null;
  31940. }
  31941. // Check if we need to recreate the submeshes
  31942. if (this.subMeshes && this.subMeshes.length > 0) {
  31943. var ib = this.getIndices();
  31944. if (!ib) {
  31945. return null;
  31946. }
  31947. var totalIndices = ib.length;
  31948. var needToRecreate = false;
  31949. if (force) {
  31950. needToRecreate = true;
  31951. }
  31952. else {
  31953. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31954. var submesh = _a[_i];
  31955. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31956. needToRecreate = true;
  31957. break;
  31958. }
  31959. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31960. needToRecreate = true;
  31961. break;
  31962. }
  31963. }
  31964. }
  31965. if (!needToRecreate) {
  31966. return this.subMeshes[0];
  31967. }
  31968. }
  31969. this.releaseSubMeshes();
  31970. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31971. };
  31972. Mesh.prototype.subdivide = function (count) {
  31973. if (count < 1) {
  31974. return;
  31975. }
  31976. var totalIndices = this.getTotalIndices();
  31977. var subdivisionSize = (totalIndices / count) | 0;
  31978. var offset = 0;
  31979. // Ensure that subdivisionSize is a multiple of 3
  31980. while (subdivisionSize % 3 !== 0) {
  31981. subdivisionSize++;
  31982. }
  31983. this.releaseSubMeshes();
  31984. for (var index = 0; index < count; index++) {
  31985. if (offset >= totalIndices) {
  31986. break;
  31987. }
  31988. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31989. offset += subdivisionSize;
  31990. }
  31991. this.synchronizeInstances();
  31992. };
  31993. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31994. if (updatable === void 0) { updatable = false; }
  31995. if (!this._geometry) {
  31996. var vertexData = new BABYLON.VertexData();
  31997. vertexData.set(data, kind);
  31998. var scene = this.getScene();
  31999. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32000. }
  32001. else {
  32002. this._geometry.setVerticesData(kind, data, updatable, stride);
  32003. }
  32004. return this;
  32005. };
  32006. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32007. if (updatable === void 0) { updatable = true; }
  32008. var vb = this.getVertexBuffer(kind);
  32009. if (!vb || vb.isUpdatable() === updatable) {
  32010. return;
  32011. }
  32012. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32013. };
  32014. /**
  32015. * Sets the mesh VertexBuffer.
  32016. * Returns the Mesh.
  32017. */
  32018. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32019. if (!this._geometry) {
  32020. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32021. }
  32022. this._geometry.setVerticesBuffer(buffer);
  32023. return this;
  32024. };
  32025. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32026. if (!this._geometry) {
  32027. return this;
  32028. }
  32029. if (!makeItUnique) {
  32030. this._geometry.updateVerticesData(kind, data, updateExtends);
  32031. }
  32032. else {
  32033. this.makeGeometryUnique();
  32034. this.updateVerticesData(kind, data, updateExtends, false);
  32035. }
  32036. return this;
  32037. };
  32038. /**
  32039. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32040. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32041. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32042. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32043. * Returns the Mesh.
  32044. */
  32045. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32046. if (computeNormals === void 0) { computeNormals = true; }
  32047. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32048. if (!positions) {
  32049. return this;
  32050. }
  32051. positionFunction(positions);
  32052. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32053. if (computeNormals) {
  32054. var indices = this.getIndices();
  32055. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32056. if (!normals) {
  32057. return this;
  32058. }
  32059. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32060. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32061. }
  32062. return this;
  32063. };
  32064. /**
  32065. * Creates a un-shared specific occurence of the geometry for the mesh.
  32066. * Returns the Mesh.
  32067. */
  32068. Mesh.prototype.makeGeometryUnique = function () {
  32069. if (!this._geometry) {
  32070. return this;
  32071. }
  32072. var oldGeometry = this._geometry;
  32073. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32074. oldGeometry.releaseForMesh(this, true);
  32075. geometry.applyToMesh(this);
  32076. return this;
  32077. };
  32078. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32079. if (totalVertices === void 0) { totalVertices = null; }
  32080. if (updatable === void 0) { updatable = false; }
  32081. if (!this._geometry) {
  32082. var vertexData = new BABYLON.VertexData();
  32083. vertexData.indices = indices;
  32084. var scene = this.getScene();
  32085. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32086. }
  32087. else {
  32088. this._geometry.setIndices(indices, totalVertices, updatable);
  32089. }
  32090. return this;
  32091. };
  32092. /**
  32093. * Update the current index buffer
  32094. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32095. * Returns the Mesh.
  32096. */
  32097. Mesh.prototype.updateIndices = function (indices, offset) {
  32098. if (!this._geometry) {
  32099. return this;
  32100. }
  32101. this._geometry.updateIndices(indices, offset);
  32102. return this;
  32103. };
  32104. /**
  32105. * Invert the geometry to move from a right handed system to a left handed one.
  32106. * Returns the Mesh.
  32107. */
  32108. Mesh.prototype.toLeftHanded = function () {
  32109. if (!this._geometry) {
  32110. return this;
  32111. }
  32112. this._geometry.toLeftHanded();
  32113. return this;
  32114. };
  32115. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32116. if (!this._geometry) {
  32117. return this;
  32118. }
  32119. var engine = this.getScene().getEngine();
  32120. // Wireframe
  32121. var indexToBind;
  32122. if (this._unIndexed) {
  32123. indexToBind = null;
  32124. }
  32125. else {
  32126. switch (fillMode) {
  32127. case BABYLON.Material.PointFillMode:
  32128. indexToBind = null;
  32129. break;
  32130. case BABYLON.Material.WireFrameFillMode:
  32131. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32132. break;
  32133. default:
  32134. case BABYLON.Material.TriangleFillMode:
  32135. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32136. break;
  32137. }
  32138. }
  32139. // VBOs
  32140. this._geometry._bind(effect, indexToBind);
  32141. return this;
  32142. };
  32143. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32144. if (alternate === void 0) { alternate = false; }
  32145. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32146. return this;
  32147. }
  32148. this.onBeforeDrawObservable.notifyObservers(this);
  32149. var scene = this.getScene();
  32150. var engine = scene.getEngine();
  32151. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32152. // or triangles as points
  32153. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32154. }
  32155. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32156. // Triangles as wireframe
  32157. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32158. }
  32159. else {
  32160. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32161. }
  32162. if (scene._isAlternateRenderingEnabled && !alternate) {
  32163. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32164. if (!effect || !scene.activeCamera) {
  32165. return this;
  32166. }
  32167. scene._switchToAlternateCameraConfiguration(true);
  32168. this._effectiveMaterial.bindView(effect);
  32169. this._effectiveMaterial.bindViewProjection(effect);
  32170. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32171. this._draw(subMesh, fillMode, instancesCount, true);
  32172. engine.setViewport(scene.activeCamera.viewport);
  32173. scene._switchToAlternateCameraConfiguration(false);
  32174. this._effectiveMaterial.bindView(effect);
  32175. this._effectiveMaterial.bindViewProjection(effect);
  32176. }
  32177. return this;
  32178. };
  32179. /**
  32180. * Registers for this mesh a javascript function called just before the rendering process.
  32181. * This function is passed the current mesh.
  32182. * Return the Mesh.
  32183. */
  32184. Mesh.prototype.registerBeforeRender = function (func) {
  32185. this.onBeforeRenderObservable.add(func);
  32186. return this;
  32187. };
  32188. /**
  32189. * Disposes a previously registered javascript function called before the rendering.
  32190. * This function is passed the current mesh.
  32191. * Returns the Mesh.
  32192. */
  32193. Mesh.prototype.unregisterBeforeRender = function (func) {
  32194. this.onBeforeRenderObservable.removeCallback(func);
  32195. return this;
  32196. };
  32197. /**
  32198. * Registers for this mesh a javascript function called just after the rendering is complete.
  32199. * This function is passed the current mesh.
  32200. * Returns the Mesh.
  32201. */
  32202. Mesh.prototype.registerAfterRender = function (func) {
  32203. this.onAfterRenderObservable.add(func);
  32204. return this;
  32205. };
  32206. /**
  32207. * Disposes a previously registered javascript function called after the rendering.
  32208. * This function is passed the current mesh.
  32209. * Return the Mesh.
  32210. */
  32211. Mesh.prototype.unregisterAfterRender = function (func) {
  32212. this.onAfterRenderObservable.removeCallback(func);
  32213. return this;
  32214. };
  32215. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32216. var scene = this.getScene();
  32217. this._batchCache.mustReturn = false;
  32218. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32219. this._batchCache.visibleInstances[subMeshId] = null;
  32220. if (this._visibleInstances) {
  32221. var currentRenderId = scene.getRenderId();
  32222. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32223. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32224. var selfRenderId = this._renderId;
  32225. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32226. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32227. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32228. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32229. }
  32230. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32231. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32232. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32233. this._batchCache.mustReturn = true;
  32234. return this._batchCache;
  32235. }
  32236. if (currentRenderId !== selfRenderId) {
  32237. this._batchCache.renderSelf[subMeshId] = false;
  32238. }
  32239. }
  32240. this._renderIdForInstances[subMeshId] = currentRenderId;
  32241. }
  32242. return this._batchCache;
  32243. };
  32244. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32245. var visibleInstances = batch.visibleInstances[subMesh._id];
  32246. if (!visibleInstances) {
  32247. return this;
  32248. }
  32249. var matricesCount = visibleInstances.length + 1;
  32250. var bufferSize = matricesCount * 16 * 4;
  32251. var currentInstancesBufferSize = this._instancesBufferSize;
  32252. var instancesBuffer = this._instancesBuffer;
  32253. while (this._instancesBufferSize < bufferSize) {
  32254. this._instancesBufferSize *= 2;
  32255. }
  32256. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32257. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32258. }
  32259. var offset = 0;
  32260. var instancesCount = 0;
  32261. var world = this.getWorldMatrix();
  32262. if (batch.renderSelf[subMesh._id]) {
  32263. world.copyToArray(this._instancesData, offset);
  32264. offset += 16;
  32265. instancesCount++;
  32266. }
  32267. if (visibleInstances) {
  32268. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32269. var instance = visibleInstances[instanceIndex];
  32270. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32271. offset += 16;
  32272. instancesCount++;
  32273. }
  32274. }
  32275. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32276. if (instancesBuffer) {
  32277. instancesBuffer.dispose();
  32278. }
  32279. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32280. this._instancesBuffer = instancesBuffer;
  32281. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32282. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32283. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32284. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32285. }
  32286. else {
  32287. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32288. }
  32289. this._bind(subMesh, effect, fillMode);
  32290. this._draw(subMesh, fillMode, instancesCount);
  32291. engine.unbindInstanceAttributes();
  32292. return this;
  32293. };
  32294. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32295. var scene = this.getScene();
  32296. var engine = scene.getEngine();
  32297. if (hardwareInstancedRendering) {
  32298. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32299. }
  32300. else {
  32301. if (batch.renderSelf[subMesh._id]) {
  32302. // Draw
  32303. if (onBeforeDraw) {
  32304. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32305. }
  32306. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32307. }
  32308. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32309. if (visibleInstancesForSubMesh) {
  32310. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32311. var instance = visibleInstancesForSubMesh[instanceIndex];
  32312. // World
  32313. var world = instance.getWorldMatrix();
  32314. if (onBeforeDraw) {
  32315. onBeforeDraw(true, world, effectiveMaterial);
  32316. }
  32317. // Draw
  32318. this._draw(subMesh, fillMode);
  32319. }
  32320. }
  32321. }
  32322. return this;
  32323. };
  32324. /**
  32325. * 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
  32326. * @param subMesh defines the subMesh to render
  32327. * @param enableAlphaMode defines if alpha mode can be changed
  32328. * @returns the current mesh
  32329. */
  32330. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32331. this._checkOcclusionQuery();
  32332. if (this._isOccluded) {
  32333. return this;
  32334. }
  32335. var scene = this.getScene();
  32336. // Managing instances
  32337. var batch = this._getInstancesRenderList(subMesh._id);
  32338. if (batch.mustReturn) {
  32339. return this;
  32340. }
  32341. // Checking geometry state
  32342. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32343. return this;
  32344. }
  32345. this.onBeforeRenderObservable.notifyObservers(this);
  32346. var engine = scene.getEngine();
  32347. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32348. // Material
  32349. var material = subMesh.getMaterial();
  32350. if (!material) {
  32351. return this;
  32352. }
  32353. this._effectiveMaterial = material;
  32354. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32355. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32356. return this;
  32357. }
  32358. }
  32359. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32360. return this;
  32361. }
  32362. // Alpha mode
  32363. if (enableAlphaMode) {
  32364. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32365. }
  32366. // Outline - step 1
  32367. var savedDepthWrite = engine.getDepthWrite();
  32368. if (this.renderOutline) {
  32369. engine.setDepthWrite(false);
  32370. scene.getOutlineRenderer().render(subMesh, batch);
  32371. engine.setDepthWrite(savedDepthWrite);
  32372. }
  32373. var effect;
  32374. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32375. effect = subMesh.effect;
  32376. }
  32377. else {
  32378. effect = this._effectiveMaterial.getEffect();
  32379. }
  32380. if (!effect) {
  32381. return this;
  32382. }
  32383. var sideOrientation = this.overrideMaterialSideOrientation;
  32384. if (sideOrientation == null) {
  32385. sideOrientation = this._effectiveMaterial.sideOrientation;
  32386. if (this._getWorldMatrixDeterminant() < 0) {
  32387. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32388. }
  32389. }
  32390. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32391. if (this._effectiveMaterial.forceDepthWrite) {
  32392. engine.setDepthWrite(true);
  32393. }
  32394. // Bind
  32395. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32396. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32397. this._bind(subMesh, effect, fillMode);
  32398. }
  32399. var world = this.getWorldMatrix();
  32400. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32401. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32402. }
  32403. else {
  32404. this._effectiveMaterial.bind(world, this);
  32405. }
  32406. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32407. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32408. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32409. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32410. }
  32411. // Draw
  32412. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32413. // Unbind
  32414. this._effectiveMaterial.unbind();
  32415. // Outline - step 2
  32416. if (this.renderOutline && savedDepthWrite) {
  32417. engine.setDepthWrite(true);
  32418. engine.setColorWrite(false);
  32419. scene.getOutlineRenderer().render(subMesh, batch);
  32420. engine.setColorWrite(true);
  32421. }
  32422. // Overlay
  32423. if (this.renderOverlay) {
  32424. var currentMode = engine.getAlphaMode();
  32425. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32426. scene.getOutlineRenderer().render(subMesh, batch, true);
  32427. engine.setAlphaMode(currentMode);
  32428. }
  32429. this.onAfterRenderObservable.notifyObservers(this);
  32430. return this;
  32431. };
  32432. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32433. if (isInstance && effectiveMaterial) {
  32434. effectiveMaterial.bindOnlyWorldMatrix(world);
  32435. }
  32436. };
  32437. /**
  32438. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32439. */
  32440. Mesh.prototype.getEmittedParticleSystems = function () {
  32441. var results = new Array();
  32442. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32443. var particleSystem = this.getScene().particleSystems[index];
  32444. if (particleSystem.emitter === this) {
  32445. results.push(particleSystem);
  32446. }
  32447. }
  32448. return results;
  32449. };
  32450. /**
  32451. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32452. */
  32453. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32454. var results = new Array();
  32455. var descendants = this.getDescendants();
  32456. descendants.push(this);
  32457. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32458. var particleSystem = this.getScene().particleSystems[index];
  32459. var emitter = particleSystem.emitter;
  32460. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32461. results.push(particleSystem);
  32462. }
  32463. }
  32464. return results;
  32465. };
  32466. /**
  32467. * Normalize matrix weights so that all vertices have a total weight set to 1
  32468. */
  32469. Mesh.prototype.cleanMatrixWeights = function () {
  32470. var epsilon = 1e-3;
  32471. var noInfluenceBoneIndex = 0.0;
  32472. if (this.skeleton) {
  32473. noInfluenceBoneIndex = this.skeleton.bones.length;
  32474. }
  32475. else {
  32476. return;
  32477. }
  32478. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32479. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32480. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32481. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32482. var influencers = this.numBoneInfluencers;
  32483. var size = matricesWeights.length;
  32484. for (var i = 0; i < size; i += 4) {
  32485. var weight = 0.0;
  32486. var firstZeroWeight = -1;
  32487. for (var j = 0; j < 4; j++) {
  32488. var w = matricesWeights[i + j];
  32489. weight += w;
  32490. if (w < epsilon && firstZeroWeight < 0) {
  32491. firstZeroWeight = j;
  32492. }
  32493. }
  32494. if (matricesWeightsExtra) {
  32495. for (var j = 0; j < 4; j++) {
  32496. var w = matricesWeightsExtra[i + j];
  32497. weight += w;
  32498. if (w < epsilon && firstZeroWeight < 0) {
  32499. firstZeroWeight = j + 4;
  32500. }
  32501. }
  32502. }
  32503. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32504. firstZeroWeight = influencers - 1;
  32505. }
  32506. if (weight > epsilon) {
  32507. var mweight = 1.0 / weight;
  32508. for (var j = 0; j < 4; j++) {
  32509. matricesWeights[i + j] *= mweight;
  32510. }
  32511. if (matricesWeightsExtra) {
  32512. for (var j = 0; j < 4; j++) {
  32513. matricesWeightsExtra[i + j] *= mweight;
  32514. }
  32515. }
  32516. }
  32517. else {
  32518. if (firstZeroWeight >= 4) {
  32519. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32520. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32521. }
  32522. else {
  32523. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32524. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32525. }
  32526. }
  32527. }
  32528. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32529. if (matricesIndicesExtra) {
  32530. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32531. }
  32532. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32533. if (matricesWeightsExtra) {
  32534. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32535. }
  32536. };
  32537. Mesh.prototype._checkDelayState = function () {
  32538. var scene = this.getScene();
  32539. if (this._geometry) {
  32540. this._geometry.load(scene);
  32541. }
  32542. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32543. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32544. this._queueLoad(scene);
  32545. }
  32546. return this;
  32547. };
  32548. Mesh.prototype._queueLoad = function (scene) {
  32549. var _this = this;
  32550. scene._addPendingData(this);
  32551. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32552. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32553. if (data instanceof ArrayBuffer) {
  32554. _this._delayLoadingFunction(data, _this);
  32555. }
  32556. else {
  32557. _this._delayLoadingFunction(JSON.parse(data), _this);
  32558. }
  32559. _this.instances.forEach(function (instance) {
  32560. instance._syncSubMeshes();
  32561. });
  32562. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32563. scene._removePendingData(_this);
  32564. }, function () { }, scene.database, getBinaryData);
  32565. return this;
  32566. };
  32567. /**
  32568. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32569. */
  32570. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32571. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32572. return false;
  32573. }
  32574. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32575. return false;
  32576. }
  32577. this._checkDelayState();
  32578. return true;
  32579. };
  32580. /**
  32581. * Sets the mesh material by the material or multiMaterial `id` property.
  32582. * The material `id` is a string identifying the material or the multiMaterial.
  32583. * This method returns the Mesh.
  32584. */
  32585. Mesh.prototype.setMaterialByID = function (id) {
  32586. var materials = this.getScene().materials;
  32587. var index;
  32588. for (index = materials.length - 1; index > -1; index--) {
  32589. if (materials[index].id === id) {
  32590. this.material = materials[index];
  32591. return this;
  32592. }
  32593. }
  32594. // Multi
  32595. var multiMaterials = this.getScene().multiMaterials;
  32596. for (index = multiMaterials.length - 1; index > -1; index--) {
  32597. if (multiMaterials[index].id === id) {
  32598. this.material = multiMaterials[index];
  32599. return this;
  32600. }
  32601. }
  32602. return this;
  32603. };
  32604. /**
  32605. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32606. */
  32607. Mesh.prototype.getAnimatables = function () {
  32608. var results = new Array();
  32609. if (this.material) {
  32610. results.push(this.material);
  32611. }
  32612. if (this.skeleton) {
  32613. results.push(this.skeleton);
  32614. }
  32615. return results;
  32616. };
  32617. /**
  32618. * Modifies the mesh geometry according to the passed transformation matrix.
  32619. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32620. * The mesh normals are modified accordingly the same transformation.
  32621. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32622. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32623. * Returns the Mesh.
  32624. */
  32625. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32626. // Position
  32627. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32628. return this;
  32629. }
  32630. var submeshes = this.subMeshes.splice(0);
  32631. this._resetPointsArrayCache();
  32632. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32633. var temp = new Array();
  32634. var index;
  32635. for (index = 0; index < data.length; index += 3) {
  32636. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32637. }
  32638. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32639. // Normals
  32640. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32641. return this;
  32642. }
  32643. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32644. temp = [];
  32645. for (index = 0; index < data.length; index += 3) {
  32646. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32647. }
  32648. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32649. // flip faces?
  32650. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32651. this.flipFaces();
  32652. }
  32653. // Restore submeshes
  32654. this.releaseSubMeshes();
  32655. this.subMeshes = submeshes;
  32656. return this;
  32657. };
  32658. /**
  32659. * Modifies the mesh geometry according to its own current World Matrix.
  32660. * The mesh World Matrix is then reset.
  32661. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32662. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32663. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32664. * Returns the Mesh.
  32665. */
  32666. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32667. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32668. this.scaling.copyFromFloats(1, 1, 1);
  32669. this.position.copyFromFloats(0, 0, 0);
  32670. this.rotation.copyFromFloats(0, 0, 0);
  32671. //only if quaternion is already set
  32672. if (this.rotationQuaternion) {
  32673. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32674. }
  32675. this._worldMatrix = BABYLON.Matrix.Identity();
  32676. return this;
  32677. };
  32678. Object.defineProperty(Mesh.prototype, "_positions", {
  32679. // Cache
  32680. get: function () {
  32681. if (this._geometry) {
  32682. return this._geometry._positions;
  32683. }
  32684. return null;
  32685. },
  32686. enumerable: true,
  32687. configurable: true
  32688. });
  32689. Mesh.prototype._resetPointsArrayCache = function () {
  32690. if (this._geometry) {
  32691. this._geometry._resetPointsArrayCache();
  32692. }
  32693. return this;
  32694. };
  32695. Mesh.prototype._generatePointsArray = function () {
  32696. if (this._geometry) {
  32697. return this._geometry._generatePointsArray();
  32698. }
  32699. return false;
  32700. };
  32701. /**
  32702. * Returns a new Mesh object generated from the current mesh properties.
  32703. * This method must not get confused with createInstance().
  32704. * The parameter `name` is a string, the name given to the new mesh.
  32705. * The optional parameter `newParent` can be any Node object (default `null`).
  32706. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32707. * 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.
  32708. */
  32709. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32710. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32711. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32712. };
  32713. /**
  32714. * Releases resources associated with this mesh.
  32715. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32716. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32717. */
  32718. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32719. var _this = this;
  32720. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32721. this.morphTargetManager = null;
  32722. if (this._geometry) {
  32723. this._geometry.releaseForMesh(this, true);
  32724. }
  32725. // Sources
  32726. var meshes = this.getScene().meshes;
  32727. meshes.forEach(function (abstractMesh) {
  32728. var mesh = abstractMesh;
  32729. if (mesh._source && mesh._source === _this) {
  32730. mesh._source = null;
  32731. }
  32732. });
  32733. this._source = null;
  32734. // Instances
  32735. if (this._instancesBuffer) {
  32736. this._instancesBuffer.dispose();
  32737. this._instancesBuffer = null;
  32738. }
  32739. while (this.instances.length) {
  32740. this.instances[0].dispose();
  32741. }
  32742. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32743. };
  32744. /**
  32745. * Modifies the mesh geometry according to a displacement map.
  32746. * 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.
  32747. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32748. * This method returns nothing.
  32749. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32750. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32751. * 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.
  32752. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32753. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32754. *
  32755. * Returns the Mesh.
  32756. */
  32757. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32758. var _this = this;
  32759. var scene = this.getScene();
  32760. var onload = function (img) {
  32761. // Getting height map data
  32762. var canvas = document.createElement("canvas");
  32763. var context = canvas.getContext("2d");
  32764. var heightMapWidth = img.width;
  32765. var heightMapHeight = img.height;
  32766. canvas.width = heightMapWidth;
  32767. canvas.height = heightMapHeight;
  32768. context.drawImage(img, 0, 0);
  32769. // Create VertexData from map data
  32770. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32771. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32772. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32773. //execute success callback, if set
  32774. if (onSuccess) {
  32775. onSuccess(_this);
  32776. }
  32777. };
  32778. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32779. return this;
  32780. };
  32781. /**
  32782. * Modifies the mesh geometry according to a displacementMap buffer.
  32783. * 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.
  32784. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32785. * This method returns nothing.
  32786. * 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.
  32787. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32788. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32789. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32790. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32791. *
  32792. * Returns the Mesh.
  32793. */
  32794. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32795. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32796. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32797. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32798. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32799. return this;
  32800. }
  32801. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32802. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32803. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32804. var position = BABYLON.Vector3.Zero();
  32805. var normal = BABYLON.Vector3.Zero();
  32806. var uv = BABYLON.Vector2.Zero();
  32807. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32808. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32809. for (var index = 0; index < positions.length; index += 3) {
  32810. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32811. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32812. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32813. // Compute height
  32814. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32815. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32816. var pos = (u + v * heightMapWidth) * 4;
  32817. var r = buffer[pos] / 255.0;
  32818. var g = buffer[pos + 1] / 255.0;
  32819. var b = buffer[pos + 2] / 255.0;
  32820. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32821. normal.normalize();
  32822. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32823. position = position.add(normal);
  32824. position.toArray(positions, index);
  32825. }
  32826. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32827. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32828. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32829. return this;
  32830. };
  32831. /**
  32832. * Modify the mesh to get a flat shading rendering.
  32833. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32834. * This method returns the Mesh.
  32835. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32836. */
  32837. Mesh.prototype.convertToFlatShadedMesh = function () {
  32838. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32839. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32840. var kinds = this.getVerticesDataKinds();
  32841. var vbs = {};
  32842. var data = {};
  32843. var newdata = {};
  32844. var updatableNormals = false;
  32845. var kindIndex;
  32846. var kind;
  32847. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32848. kind = kinds[kindIndex];
  32849. var vertexBuffer = this.getVertexBuffer(kind);
  32850. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32851. updatableNormals = vertexBuffer.isUpdatable();
  32852. kinds.splice(kindIndex, 1);
  32853. kindIndex--;
  32854. continue;
  32855. }
  32856. vbs[kind] = vertexBuffer;
  32857. data[kind] = vbs[kind].getData();
  32858. newdata[kind] = [];
  32859. }
  32860. // Save previous submeshes
  32861. var previousSubmeshes = this.subMeshes.slice(0);
  32862. var indices = this.getIndices();
  32863. var totalIndices = this.getTotalIndices();
  32864. // Generating unique vertices per face
  32865. var index;
  32866. for (index = 0; index < totalIndices; index++) {
  32867. var vertexIndex = indices[index];
  32868. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32869. kind = kinds[kindIndex];
  32870. var stride = vbs[kind].getStrideSize();
  32871. for (var offset = 0; offset < stride; offset++) {
  32872. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32873. }
  32874. }
  32875. }
  32876. // Updating faces & normal
  32877. var normals = [];
  32878. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32879. for (index = 0; index < totalIndices; index += 3) {
  32880. indices[index] = index;
  32881. indices[index + 1] = index + 1;
  32882. indices[index + 2] = index + 2;
  32883. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32884. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32885. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32886. var p1p2 = p1.subtract(p2);
  32887. var p3p2 = p3.subtract(p2);
  32888. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32889. // Store same normals for every vertex
  32890. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32891. normals.push(normal.x);
  32892. normals.push(normal.y);
  32893. normals.push(normal.z);
  32894. }
  32895. }
  32896. this.setIndices(indices);
  32897. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32898. // Updating vertex buffers
  32899. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32900. kind = kinds[kindIndex];
  32901. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32902. }
  32903. // Updating submeshes
  32904. this.releaseSubMeshes();
  32905. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32906. var previousOne = previousSubmeshes[submeshIndex];
  32907. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32908. }
  32909. this.synchronizeInstances();
  32910. return this;
  32911. };
  32912. /**
  32913. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32914. * In other words, more vertices, no more indices and a single bigger VBO.
  32915. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32916. * Returns the Mesh.
  32917. */
  32918. Mesh.prototype.convertToUnIndexedMesh = function () {
  32919. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32920. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32921. var kinds = this.getVerticesDataKinds();
  32922. var vbs = {};
  32923. var data = {};
  32924. var newdata = {};
  32925. var kindIndex;
  32926. var kind;
  32927. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32928. kind = kinds[kindIndex];
  32929. var vertexBuffer = this.getVertexBuffer(kind);
  32930. vbs[kind] = vertexBuffer;
  32931. data[kind] = vbs[kind].getData();
  32932. newdata[kind] = [];
  32933. }
  32934. // Save previous submeshes
  32935. var previousSubmeshes = this.subMeshes.slice(0);
  32936. var indices = this.getIndices();
  32937. var totalIndices = this.getTotalIndices();
  32938. // Generating unique vertices per face
  32939. var index;
  32940. for (index = 0; index < totalIndices; index++) {
  32941. var vertexIndex = indices[index];
  32942. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32943. kind = kinds[kindIndex];
  32944. var stride = vbs[kind].getStrideSize();
  32945. for (var offset = 0; offset < stride; offset++) {
  32946. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32947. }
  32948. }
  32949. }
  32950. // Updating indices
  32951. for (index = 0; index < totalIndices; index += 3) {
  32952. indices[index] = index;
  32953. indices[index + 1] = index + 1;
  32954. indices[index + 2] = index + 2;
  32955. }
  32956. this.setIndices(indices);
  32957. // Updating vertex buffers
  32958. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32959. kind = kinds[kindIndex];
  32960. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32961. }
  32962. // Updating submeshes
  32963. this.releaseSubMeshes();
  32964. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32965. var previousOne = previousSubmeshes[submeshIndex];
  32966. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32967. }
  32968. this._unIndexed = true;
  32969. this.synchronizeInstances();
  32970. return this;
  32971. };
  32972. /**
  32973. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32974. * This method returns the Mesh.
  32975. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32976. */
  32977. Mesh.prototype.flipFaces = function (flipNormals) {
  32978. if (flipNormals === void 0) { flipNormals = false; }
  32979. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32980. var i;
  32981. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32982. for (i = 0; i < vertex_data.normals.length; i++) {
  32983. vertex_data.normals[i] *= -1;
  32984. }
  32985. }
  32986. if (vertex_data.indices) {
  32987. var temp;
  32988. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32989. // reassign indices
  32990. temp = vertex_data.indices[i + 1];
  32991. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32992. vertex_data.indices[i + 2] = temp;
  32993. }
  32994. }
  32995. vertex_data.applyToMesh(this);
  32996. return this;
  32997. };
  32998. // Instances
  32999. /**
  33000. * Creates a new InstancedMesh object from the mesh model.
  33001. * An instance shares the same properties and the same material than its model.
  33002. * Only these properties of each instance can then be set individually :
  33003. * - position
  33004. * - rotation
  33005. * - rotationQuaternion
  33006. * - setPivotMatrix
  33007. * - scaling
  33008. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33009. * Warning : this method is not supported for Line mesh and LineSystem
  33010. */
  33011. Mesh.prototype.createInstance = function (name) {
  33012. return new BABYLON.InstancedMesh(name, this);
  33013. };
  33014. /**
  33015. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33016. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33017. * This method returns the Mesh.
  33018. */
  33019. Mesh.prototype.synchronizeInstances = function () {
  33020. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33021. var instance = this.instances[instanceIndex];
  33022. instance._syncSubMeshes();
  33023. }
  33024. return this;
  33025. };
  33026. /**
  33027. * Simplify the mesh according to the given array of settings.
  33028. * Function will return immediately and will simplify async. It returns the Mesh.
  33029. * @param settings a collection of simplification settings.
  33030. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33031. * @param type the type of simplification to run.
  33032. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33033. */
  33034. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33035. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33036. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33037. this.getScene().simplificationQueue.addTask({
  33038. settings: settings,
  33039. parallelProcessing: parallelProcessing,
  33040. mesh: this,
  33041. simplificationType: simplificationType,
  33042. successCallback: successCallback
  33043. });
  33044. return this;
  33045. };
  33046. /**
  33047. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33048. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33049. * This should be used together with the simplification to avoid disappearing triangles.
  33050. * Returns the Mesh.
  33051. * @param successCallback an optional success callback to be called after the optimization finished.
  33052. */
  33053. Mesh.prototype.optimizeIndices = function (successCallback) {
  33054. var _this = this;
  33055. var indices = this.getIndices();
  33056. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33057. if (!positions || !indices) {
  33058. return this;
  33059. }
  33060. var vectorPositions = new Array();
  33061. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33062. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33063. }
  33064. var dupes = new Array();
  33065. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33066. var realPos = vectorPositions.length - 1 - iteration;
  33067. var testedPosition = vectorPositions[realPos];
  33068. for (var j = 0; j < realPos; ++j) {
  33069. var againstPosition = vectorPositions[j];
  33070. if (testedPosition.equals(againstPosition)) {
  33071. dupes[realPos] = j;
  33072. break;
  33073. }
  33074. }
  33075. }, function () {
  33076. for (var i = 0; i < indices.length; ++i) {
  33077. indices[i] = dupes[indices[i]] || indices[i];
  33078. }
  33079. //indices are now reordered
  33080. var originalSubMeshes = _this.subMeshes.slice(0);
  33081. _this.setIndices(indices);
  33082. _this.subMeshes = originalSubMeshes;
  33083. if (successCallback) {
  33084. successCallback(_this);
  33085. }
  33086. });
  33087. return this;
  33088. };
  33089. Mesh.prototype.serialize = function (serializationObject) {
  33090. serializationObject.name = this.name;
  33091. serializationObject.id = this.id;
  33092. serializationObject.type = this.getClassName();
  33093. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33094. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33095. }
  33096. serializationObject.position = this.position.asArray();
  33097. if (this.rotationQuaternion) {
  33098. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33099. }
  33100. else if (this.rotation) {
  33101. serializationObject.rotation = this.rotation.asArray();
  33102. }
  33103. serializationObject.scaling = this.scaling.asArray();
  33104. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33105. serializationObject.isEnabled = this.isEnabled(false);
  33106. serializationObject.isVisible = this.isVisible;
  33107. serializationObject.infiniteDistance = this.infiniteDistance;
  33108. serializationObject.pickable = this.isPickable;
  33109. serializationObject.receiveShadows = this.receiveShadows;
  33110. serializationObject.billboardMode = this.billboardMode;
  33111. serializationObject.visibility = this.visibility;
  33112. serializationObject.checkCollisions = this.checkCollisions;
  33113. serializationObject.isBlocker = this.isBlocker;
  33114. // Parent
  33115. if (this.parent) {
  33116. serializationObject.parentId = this.parent.id;
  33117. }
  33118. // Geometry
  33119. serializationObject.isUnIndexed = this.isUnIndexed;
  33120. var geometry = this._geometry;
  33121. if (geometry) {
  33122. var geometryId = geometry.id;
  33123. serializationObject.geometryId = geometryId;
  33124. // SubMeshes
  33125. serializationObject.subMeshes = [];
  33126. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33127. var subMesh = this.subMeshes[subIndex];
  33128. serializationObject.subMeshes.push({
  33129. materialIndex: subMesh.materialIndex,
  33130. verticesStart: subMesh.verticesStart,
  33131. verticesCount: subMesh.verticesCount,
  33132. indexStart: subMesh.indexStart,
  33133. indexCount: subMesh.indexCount
  33134. });
  33135. }
  33136. }
  33137. // Material
  33138. if (this.material) {
  33139. serializationObject.materialId = this.material.id;
  33140. }
  33141. else {
  33142. this.material = null;
  33143. }
  33144. // Morph targets
  33145. if (this.morphTargetManager) {
  33146. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33147. }
  33148. // Skeleton
  33149. if (this.skeleton) {
  33150. serializationObject.skeletonId = this.skeleton.id;
  33151. }
  33152. // Physics
  33153. //TODO implement correct serialization for physics impostors.
  33154. var impostor = this.getPhysicsImpostor();
  33155. if (impostor) {
  33156. serializationObject.physicsMass = impostor.getParam("mass");
  33157. serializationObject.physicsFriction = impostor.getParam("friction");
  33158. serializationObject.physicsRestitution = impostor.getParam("mass");
  33159. serializationObject.physicsImpostor = impostor.type;
  33160. }
  33161. // Metadata
  33162. if (this.metadata) {
  33163. serializationObject.metadata = this.metadata;
  33164. }
  33165. // Instances
  33166. serializationObject.instances = [];
  33167. for (var index = 0; index < this.instances.length; index++) {
  33168. var instance = this.instances[index];
  33169. var serializationInstance = {
  33170. name: instance.name,
  33171. id: instance.id,
  33172. position: instance.position.asArray(),
  33173. scaling: instance.scaling.asArray()
  33174. };
  33175. if (instance.rotationQuaternion) {
  33176. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33177. }
  33178. else if (instance.rotation) {
  33179. serializationInstance.rotation = instance.rotation.asArray();
  33180. }
  33181. serializationObject.instances.push(serializationInstance);
  33182. // Animations
  33183. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33184. serializationInstance.ranges = instance.serializeAnimationRanges();
  33185. }
  33186. //
  33187. // Animations
  33188. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33189. serializationObject.ranges = this.serializeAnimationRanges();
  33190. // Layer mask
  33191. serializationObject.layerMask = this.layerMask;
  33192. // Alpha
  33193. serializationObject.alphaIndex = this.alphaIndex;
  33194. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33195. // Overlay
  33196. serializationObject.overlayAlpha = this.overlayAlpha;
  33197. serializationObject.overlayColor = this.overlayColor.asArray();
  33198. serializationObject.renderOverlay = this.renderOverlay;
  33199. // Fog
  33200. serializationObject.applyFog = this.applyFog;
  33201. // Action Manager
  33202. if (this.actionManager) {
  33203. serializationObject.actions = this.actionManager.serialize(this.name);
  33204. }
  33205. };
  33206. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33207. if (!this.geometry) {
  33208. return;
  33209. }
  33210. this._markSubMeshesAsAttributesDirty();
  33211. var morphTargetManager = this._morphTargetManager;
  33212. if (morphTargetManager && morphTargetManager.vertexCount) {
  33213. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33214. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33215. this.morphTargetManager = null;
  33216. return;
  33217. }
  33218. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33219. var morphTarget = morphTargetManager.getActiveTarget(index);
  33220. var positions = morphTarget.getPositions();
  33221. if (!positions) {
  33222. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33223. return;
  33224. }
  33225. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33226. var normals = morphTarget.getNormals();
  33227. if (normals) {
  33228. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33229. }
  33230. var tangents = morphTarget.getTangents();
  33231. if (tangents) {
  33232. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33233. }
  33234. }
  33235. }
  33236. else {
  33237. var index = 0;
  33238. // Positions
  33239. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33240. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33241. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33242. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33243. }
  33244. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33245. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33246. }
  33247. index++;
  33248. }
  33249. }
  33250. };
  33251. // Statics
  33252. /**
  33253. * Returns a new Mesh object parsed from the source provided.
  33254. * The parameter `parsedMesh` is the source.
  33255. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33256. */
  33257. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33258. var mesh;
  33259. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33260. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33261. }
  33262. else {
  33263. mesh = new Mesh(parsedMesh.name, scene);
  33264. }
  33265. mesh.id = parsedMesh.id;
  33266. if (BABYLON.Tags) {
  33267. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33268. }
  33269. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33270. if (parsedMesh.metadata !== undefined) {
  33271. mesh.metadata = parsedMesh.metadata;
  33272. }
  33273. if (parsedMesh.rotationQuaternion) {
  33274. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33275. }
  33276. else if (parsedMesh.rotation) {
  33277. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33278. }
  33279. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33280. if (parsedMesh.localMatrix) {
  33281. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33282. }
  33283. else if (parsedMesh.pivotMatrix) {
  33284. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33285. }
  33286. mesh.setEnabled(parsedMesh.isEnabled);
  33287. mesh.isVisible = parsedMesh.isVisible;
  33288. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33289. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33290. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33291. if (parsedMesh.applyFog !== undefined) {
  33292. mesh.applyFog = parsedMesh.applyFog;
  33293. }
  33294. if (parsedMesh.pickable !== undefined) {
  33295. mesh.isPickable = parsedMesh.pickable;
  33296. }
  33297. if (parsedMesh.alphaIndex !== undefined) {
  33298. mesh.alphaIndex = parsedMesh.alphaIndex;
  33299. }
  33300. mesh.receiveShadows = parsedMesh.receiveShadows;
  33301. mesh.billboardMode = parsedMesh.billboardMode;
  33302. if (parsedMesh.visibility !== undefined) {
  33303. mesh.visibility = parsedMesh.visibility;
  33304. }
  33305. mesh.checkCollisions = parsedMesh.checkCollisions;
  33306. if (parsedMesh.isBlocker !== undefined) {
  33307. mesh.isBlocker = parsedMesh.isBlocker;
  33308. }
  33309. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33310. // freezeWorldMatrix
  33311. if (parsedMesh.freezeWorldMatrix) {
  33312. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33313. }
  33314. // Parent
  33315. if (parsedMesh.parentId) {
  33316. mesh._waitingParentId = parsedMesh.parentId;
  33317. }
  33318. // Actions
  33319. if (parsedMesh.actions !== undefined) {
  33320. mesh._waitingActions = parsedMesh.actions;
  33321. }
  33322. // Overlay
  33323. if (parsedMesh.overlayAlpha !== undefined) {
  33324. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33325. }
  33326. if (parsedMesh.overlayColor !== undefined) {
  33327. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33328. }
  33329. if (parsedMesh.renderOverlay !== undefined) {
  33330. mesh.renderOverlay = parsedMesh.renderOverlay;
  33331. }
  33332. // Geometry
  33333. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33334. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33335. if (parsedMesh.delayLoadingFile) {
  33336. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33337. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33338. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33339. if (parsedMesh._binaryInfo) {
  33340. mesh._binaryInfo = parsedMesh._binaryInfo;
  33341. }
  33342. mesh._delayInfo = [];
  33343. if (parsedMesh.hasUVs) {
  33344. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33345. }
  33346. if (parsedMesh.hasUVs2) {
  33347. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33348. }
  33349. if (parsedMesh.hasUVs3) {
  33350. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33351. }
  33352. if (parsedMesh.hasUVs4) {
  33353. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33354. }
  33355. if (parsedMesh.hasUVs5) {
  33356. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33357. }
  33358. if (parsedMesh.hasUVs6) {
  33359. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33360. }
  33361. if (parsedMesh.hasColors) {
  33362. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33363. }
  33364. if (parsedMesh.hasMatricesIndices) {
  33365. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33366. }
  33367. if (parsedMesh.hasMatricesWeights) {
  33368. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33369. }
  33370. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33371. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33372. mesh._checkDelayState();
  33373. }
  33374. }
  33375. else {
  33376. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33377. }
  33378. // Material
  33379. if (parsedMesh.materialId) {
  33380. mesh.setMaterialByID(parsedMesh.materialId);
  33381. }
  33382. else {
  33383. mesh.material = null;
  33384. }
  33385. // Morph targets
  33386. if (parsedMesh.morphTargetManagerId > -1) {
  33387. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33388. }
  33389. // Skeleton
  33390. if (parsedMesh.skeletonId > -1) {
  33391. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33392. if (parsedMesh.numBoneInfluencers) {
  33393. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33394. }
  33395. }
  33396. // Animations
  33397. if (parsedMesh.animations) {
  33398. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33399. var parsedAnimation = parsedMesh.animations[animationIndex];
  33400. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33401. }
  33402. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33403. }
  33404. if (parsedMesh.autoAnimate) {
  33405. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33406. }
  33407. // Layer Mask
  33408. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33409. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33410. }
  33411. else {
  33412. mesh.layerMask = 0x0FFFFFFF;
  33413. }
  33414. // Physics
  33415. if (parsedMesh.physicsImpostor) {
  33416. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33417. mass: parsedMesh.physicsMass,
  33418. friction: parsedMesh.physicsFriction,
  33419. restitution: parsedMesh.physicsRestitution
  33420. }, scene);
  33421. }
  33422. // Instances
  33423. if (parsedMesh.instances) {
  33424. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33425. var parsedInstance = parsedMesh.instances[index];
  33426. var instance = mesh.createInstance(parsedInstance.name);
  33427. if (parsedInstance.id) {
  33428. instance.id = parsedInstance.id;
  33429. }
  33430. if (BABYLON.Tags) {
  33431. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33432. }
  33433. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33434. if (parsedInstance.parentId) {
  33435. instance._waitingParentId = parsedInstance.parentId;
  33436. }
  33437. if (parsedInstance.rotationQuaternion) {
  33438. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33439. }
  33440. else if (parsedInstance.rotation) {
  33441. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33442. }
  33443. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33444. instance.checkCollisions = mesh.checkCollisions;
  33445. if (parsedMesh.animations) {
  33446. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33447. parsedAnimation = parsedMesh.animations[animationIndex];
  33448. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33449. }
  33450. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33451. if (parsedMesh.autoAnimate) {
  33452. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33453. }
  33454. }
  33455. }
  33456. }
  33457. return mesh;
  33458. };
  33459. /**
  33460. * Creates a ribbon mesh.
  33461. * Please consider using the same method from the MeshBuilder class instead.
  33462. * 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.
  33463. *
  33464. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33465. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33466. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33467. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33468. * 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.
  33469. * 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.
  33470. * 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
  33471. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33472. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33473. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33474. */
  33475. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33476. if (closeArray === void 0) { closeArray = false; }
  33477. if (updatable === void 0) { updatable = false; }
  33478. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33479. pathArray: pathArray,
  33480. closeArray: closeArray,
  33481. closePath: closePath,
  33482. offset: offset,
  33483. updatable: updatable,
  33484. sideOrientation: sideOrientation,
  33485. instance: instance
  33486. }, scene);
  33487. };
  33488. /**
  33489. * Creates a plane polygonal mesh. By default, this is a disc.
  33490. * Please consider using the same method from the MeshBuilder class instead.
  33491. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33492. * 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.
  33493. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33494. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33495. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33496. */
  33497. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33498. if (scene === void 0) { scene = null; }
  33499. var options = {
  33500. radius: radius,
  33501. tessellation: tessellation,
  33502. sideOrientation: sideOrientation,
  33503. updatable: updatable
  33504. };
  33505. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33506. };
  33507. /**
  33508. * Creates a box mesh.
  33509. * Please consider using the same method from the MeshBuilder class instead.
  33510. * The parameter `size` sets the size (float) of each box side (default 1).
  33511. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33512. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33513. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33514. */
  33515. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33516. if (scene === void 0) { scene = null; }
  33517. var options = {
  33518. size: size,
  33519. sideOrientation: sideOrientation,
  33520. updatable: updatable
  33521. };
  33522. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33523. };
  33524. /**
  33525. * Creates a sphere mesh.
  33526. * Please consider using the same method from the MeshBuilder class instead.
  33527. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33528. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33529. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33530. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33531. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33532. */
  33533. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33534. var options = {
  33535. segments: segments,
  33536. diameterX: diameter,
  33537. diameterY: diameter,
  33538. diameterZ: diameter,
  33539. sideOrientation: sideOrientation,
  33540. updatable: updatable
  33541. };
  33542. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33543. };
  33544. /**
  33545. * Creates a cylinder or a cone mesh.
  33546. * Please consider using the same method from the MeshBuilder class instead.
  33547. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33548. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33549. * 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.
  33550. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33551. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33552. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33553. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33554. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33555. */
  33556. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33557. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33558. if (scene !== undefined) {
  33559. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33560. updatable = scene;
  33561. }
  33562. scene = subdivisions;
  33563. subdivisions = 1;
  33564. }
  33565. var options = {
  33566. height: height,
  33567. diameterTop: diameterTop,
  33568. diameterBottom: diameterBottom,
  33569. tessellation: tessellation,
  33570. subdivisions: subdivisions,
  33571. sideOrientation: sideOrientation,
  33572. updatable: updatable
  33573. };
  33574. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33575. };
  33576. // Torus (Code from SharpDX.org)
  33577. /**
  33578. * Creates a torus mesh.
  33579. * Please consider using the same method from the MeshBuilder class instead.
  33580. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33581. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33582. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33583. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33584. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33585. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33586. */
  33587. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33588. var options = {
  33589. diameter: diameter,
  33590. thickness: thickness,
  33591. tessellation: tessellation,
  33592. sideOrientation: sideOrientation,
  33593. updatable: updatable
  33594. };
  33595. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33596. };
  33597. /**
  33598. * Creates a torus knot mesh.
  33599. * Please consider using the same method from the MeshBuilder class instead.
  33600. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33601. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33602. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33603. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33604. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33605. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33606. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33607. */
  33608. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33609. var options = {
  33610. radius: radius,
  33611. tube: tube,
  33612. radialSegments: radialSegments,
  33613. tubularSegments: tubularSegments,
  33614. p: p,
  33615. q: q,
  33616. sideOrientation: sideOrientation,
  33617. updatable: updatable
  33618. };
  33619. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33620. };
  33621. /**
  33622. * Creates a line mesh.
  33623. * Please consider using the same method from the MeshBuilder class instead.
  33624. * 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.
  33625. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33626. * The parameter `points` is an array successive Vector3.
  33627. * 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
  33628. * When updating an instance, remember that only point positions can change, not the number of points.
  33629. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33630. */
  33631. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33632. if (scene === void 0) { scene = null; }
  33633. if (updatable === void 0) { updatable = false; }
  33634. if (instance === void 0) { instance = null; }
  33635. var options = {
  33636. points: points,
  33637. updatable: updatable,
  33638. instance: instance
  33639. };
  33640. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33641. };
  33642. /**
  33643. * Creates a dashed line mesh.
  33644. * Please consider using the same method from the MeshBuilder class instead.
  33645. * 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.
  33646. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33647. * The parameter `points` is an array successive Vector3.
  33648. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33649. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33650. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33651. * 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
  33652. * When updating an instance, remember that only point positions can change, not the number of points.
  33653. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33654. */
  33655. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33656. if (scene === void 0) { scene = null; }
  33657. var options = {
  33658. points: points,
  33659. dashSize: dashSize,
  33660. gapSize: gapSize,
  33661. dashNb: dashNb,
  33662. updatable: updatable,
  33663. instance: instance
  33664. };
  33665. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33666. };
  33667. /**
  33668. * Creates a polygon mesh.
  33669. * Please consider using the same method from the MeshBuilder class instead.
  33670. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33671. * 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.
  33672. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33673. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33674. * Remember you can only change the shape positions, not their number when updating a polygon.
  33675. */
  33676. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33677. var options = {
  33678. shape: shape,
  33679. holes: holes,
  33680. updatable: updatable,
  33681. sideOrientation: sideOrientation
  33682. };
  33683. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33684. };
  33685. /**
  33686. * Creates an extruded polygon mesh, with depth in the Y direction.
  33687. * Please consider using the same method from the MeshBuilder class instead.
  33688. */
  33689. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33690. var options = {
  33691. shape: shape,
  33692. holes: holes,
  33693. depth: depth,
  33694. updatable: updatable,
  33695. sideOrientation: sideOrientation
  33696. };
  33697. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33698. };
  33699. /**
  33700. * Creates an extruded shape mesh.
  33701. * 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.
  33702. * Please consider using the same method from the MeshBuilder class instead.
  33703. *
  33704. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33705. * 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
  33706. * extruded along the Z axis.
  33707. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33708. * 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.
  33709. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33710. * 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
  33711. * 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
  33712. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33713. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33714. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33715. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33716. */
  33717. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33718. if (scene === void 0) { scene = null; }
  33719. var options = {
  33720. shape: shape,
  33721. path: path,
  33722. scale: scale,
  33723. rotation: rotation,
  33724. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33725. sideOrientation: sideOrientation,
  33726. instance: instance,
  33727. updatable: updatable
  33728. };
  33729. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33730. };
  33731. /**
  33732. * Creates an custom extruded shape mesh.
  33733. * 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.
  33734. * Please consider using the same method from the MeshBuilder class instead.
  33735. *
  33736. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33737. * 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
  33738. * extruded along the Z axis.
  33739. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33740. * 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
  33741. * and the distance of this point from the begining of the path :
  33742. * ```javascript
  33743. * var rotationFunction = function(i, distance) {
  33744. * // do things
  33745. * return rotationValue; }
  33746. * ```
  33747. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33748. * 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
  33749. * and the distance of this point from the begining of the path :
  33750. * ```javascript
  33751. * var scaleFunction = function(i, distance) {
  33752. * // do things
  33753. * return scaleValue;}
  33754. * ```
  33755. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33756. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33757. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33758. * 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
  33759. * 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
  33760. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33761. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33762. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33763. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33764. */
  33765. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33766. var options = {
  33767. shape: shape,
  33768. path: path,
  33769. scaleFunction: scaleFunction,
  33770. rotationFunction: rotationFunction,
  33771. ribbonCloseArray: ribbonCloseArray,
  33772. ribbonClosePath: ribbonClosePath,
  33773. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33774. sideOrientation: sideOrientation,
  33775. instance: instance,
  33776. updatable: updatable
  33777. };
  33778. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33779. };
  33780. /**
  33781. * Creates lathe mesh.
  33782. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33783. * Please consider using the same method from the MeshBuilder class instead.
  33784. * 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
  33785. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33786. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33787. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33788. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33789. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33790. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33791. */
  33792. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33793. var options = {
  33794. shape: shape,
  33795. radius: radius,
  33796. tessellation: tessellation,
  33797. sideOrientation: sideOrientation,
  33798. updatable: updatable
  33799. };
  33800. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33801. };
  33802. /**
  33803. * Creates a plane mesh.
  33804. * Please consider using the same method from the MeshBuilder class instead.
  33805. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33806. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33807. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33808. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33809. */
  33810. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33811. var options = {
  33812. size: size,
  33813. width: size,
  33814. height: size,
  33815. sideOrientation: sideOrientation,
  33816. updatable: updatable
  33817. };
  33818. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33819. };
  33820. /**
  33821. * Creates a ground mesh.
  33822. * Please consider using the same method from the MeshBuilder class instead.
  33823. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33824. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33825. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33826. */
  33827. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33828. var options = {
  33829. width: width,
  33830. height: height,
  33831. subdivisions: subdivisions,
  33832. updatable: updatable
  33833. };
  33834. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33835. };
  33836. /**
  33837. * Creates a tiled ground mesh.
  33838. * Please consider using the same method from the MeshBuilder class instead.
  33839. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33840. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33841. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33842. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33843. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33844. * numbers of subdivisions on the ground width and height of each tile.
  33845. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33846. */
  33847. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33848. var options = {
  33849. xmin: xmin,
  33850. zmin: zmin,
  33851. xmax: xmax,
  33852. zmax: zmax,
  33853. subdivisions: subdivisions,
  33854. precision: precision,
  33855. updatable: updatable
  33856. };
  33857. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33858. };
  33859. /**
  33860. * Creates a ground mesh from a height map.
  33861. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33862. * Please consider using the same method from the MeshBuilder class instead.
  33863. * The parameter `url` sets the URL of the height map image resource.
  33864. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33865. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33866. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33867. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33868. * 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).
  33869. * This function is passed the newly built mesh :
  33870. * ```javascript
  33871. * function(mesh) { // do things
  33872. * return; }
  33873. * ```
  33874. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33875. */
  33876. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33877. var options = {
  33878. width: width,
  33879. height: height,
  33880. subdivisions: subdivisions,
  33881. minHeight: minHeight,
  33882. maxHeight: maxHeight,
  33883. updatable: updatable,
  33884. onReady: onReady
  33885. };
  33886. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33887. };
  33888. /**
  33889. * Creates a tube mesh.
  33890. * 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.
  33891. * Please consider using the same method from the MeshBuilder class instead.
  33892. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33893. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33894. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33895. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33896. * 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.
  33897. * It must return a radius value (positive float) :
  33898. * ```javascript
  33899. * var radiusFunction = function(i, distance) {
  33900. * // do things
  33901. * return radius; }
  33902. * ```
  33903. * 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
  33904. * 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
  33905. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33906. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33907. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33908. */
  33909. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33910. var options = {
  33911. path: path,
  33912. radius: radius,
  33913. tessellation: tessellation,
  33914. radiusFunction: radiusFunction,
  33915. arc: 1,
  33916. cap: cap,
  33917. updatable: updatable,
  33918. sideOrientation: sideOrientation,
  33919. instance: instance
  33920. };
  33921. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33922. };
  33923. /**
  33924. * Creates a polyhedron mesh.
  33925. * Please consider using the same method from the MeshBuilder class instead.
  33926. * 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
  33927. * to choose the wanted type.
  33928. * The parameter `size` (positive float, default 1) sets the polygon size.
  33929. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33930. * 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`.
  33931. * 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
  33932. * 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)`).
  33933. * 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
  33934. * 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.
  33935. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33936. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33937. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33938. */
  33939. Mesh.CreatePolyhedron = function (name, options, scene) {
  33940. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33941. };
  33942. /**
  33943. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33944. * Please consider using the same method from the MeshBuilder class instead.
  33945. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33946. * 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`).
  33947. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33948. * 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.
  33949. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33950. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33951. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33952. */
  33953. Mesh.CreateIcoSphere = function (name, options, scene) {
  33954. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33955. };
  33956. /**
  33957. * Creates a decal mesh.
  33958. * Please consider using the same method from the MeshBuilder class instead.
  33959. * 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.
  33960. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33961. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33962. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33963. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33964. */
  33965. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33966. var options = {
  33967. position: position,
  33968. normal: normal,
  33969. size: size,
  33970. angle: angle
  33971. };
  33972. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33973. };
  33974. // Skeletons
  33975. /**
  33976. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33977. */
  33978. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33979. if (!this._sourcePositions) {
  33980. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33981. if (!source) {
  33982. return this._sourcePositions;
  33983. }
  33984. this._sourcePositions = new Float32Array(source);
  33985. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33986. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33987. }
  33988. }
  33989. return this._sourcePositions;
  33990. };
  33991. /**
  33992. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33993. */
  33994. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33995. if (!this._sourceNormals) {
  33996. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33997. if (!source) {
  33998. return this._sourceNormals;
  33999. }
  34000. this._sourceNormals = new Float32Array(source);
  34001. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34002. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34003. }
  34004. }
  34005. return this._sourceNormals;
  34006. };
  34007. /**
  34008. * Updates the vertex buffer by applying transformation from the bones.
  34009. * Returns the Mesh.
  34010. *
  34011. * @param {skeleton} skeleton to apply
  34012. */
  34013. Mesh.prototype.applySkeleton = function (skeleton) {
  34014. if (!this.geometry) {
  34015. return this;
  34016. }
  34017. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34018. return this;
  34019. }
  34020. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34021. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34022. return this;
  34023. }
  34024. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34025. return this;
  34026. }
  34027. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34028. return this;
  34029. }
  34030. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34031. return this;
  34032. }
  34033. if (!this._sourcePositions) {
  34034. var submeshes = this.subMeshes.slice();
  34035. this.setPositionsForCPUSkinning();
  34036. this.subMeshes = submeshes;
  34037. }
  34038. if (!this._sourceNormals) {
  34039. this.setNormalsForCPUSkinning();
  34040. }
  34041. // positionsData checks for not being Float32Array will only pass at most once
  34042. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34043. if (!positionsData) {
  34044. return this;
  34045. }
  34046. if (!(positionsData instanceof Float32Array)) {
  34047. positionsData = new Float32Array(positionsData);
  34048. }
  34049. // normalsData checks for not being Float32Array will only pass at most once
  34050. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34051. if (!normalsData) {
  34052. return this;
  34053. }
  34054. if (!(normalsData instanceof Float32Array)) {
  34055. normalsData = new Float32Array(normalsData);
  34056. }
  34057. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34058. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34059. if (!matricesWeightsData || !matricesIndicesData) {
  34060. return this;
  34061. }
  34062. var needExtras = this.numBoneInfluencers > 4;
  34063. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34064. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34065. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34066. var tempVector3 = BABYLON.Vector3.Zero();
  34067. var finalMatrix = new BABYLON.Matrix();
  34068. var tempMatrix = new BABYLON.Matrix();
  34069. var matWeightIdx = 0;
  34070. var inf;
  34071. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34072. var weight;
  34073. for (inf = 0; inf < 4; inf++) {
  34074. weight = matricesWeightsData[matWeightIdx + inf];
  34075. if (weight > 0) {
  34076. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34077. finalMatrix.addToSelf(tempMatrix);
  34078. }
  34079. }
  34080. if (needExtras) {
  34081. for (inf = 0; inf < 4; inf++) {
  34082. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34083. if (weight > 0) {
  34084. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34085. finalMatrix.addToSelf(tempMatrix);
  34086. }
  34087. }
  34088. }
  34089. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34090. tempVector3.toArray(positionsData, index);
  34091. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34092. tempVector3.toArray(normalsData, index);
  34093. finalMatrix.reset();
  34094. }
  34095. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34096. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34097. return this;
  34098. };
  34099. // Tools
  34100. /**
  34101. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34102. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34103. */
  34104. Mesh.MinMax = function (meshes) {
  34105. var minVector = null;
  34106. var maxVector = null;
  34107. meshes.forEach(function (mesh, index, array) {
  34108. var boundingInfo = mesh.getBoundingInfo();
  34109. var boundingBox = boundingInfo.boundingBox;
  34110. if (!minVector || !maxVector) {
  34111. minVector = boundingBox.minimumWorld;
  34112. maxVector = boundingBox.maximumWorld;
  34113. }
  34114. else {
  34115. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34116. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34117. }
  34118. });
  34119. if (!minVector || !maxVector) {
  34120. return {
  34121. min: BABYLON.Vector3.Zero(),
  34122. max: BABYLON.Vector3.Zero()
  34123. };
  34124. }
  34125. return {
  34126. min: minVector,
  34127. max: maxVector
  34128. };
  34129. };
  34130. /**
  34131. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34132. */
  34133. Mesh.Center = function (meshesOrMinMaxVector) {
  34134. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34135. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34136. };
  34137. /**
  34138. * Merge the array of meshes into a single mesh for performance reasons.
  34139. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34140. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34141. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34142. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34143. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34144. */
  34145. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34146. if (disposeSource === void 0) { disposeSource = true; }
  34147. var index;
  34148. if (!allow32BitsIndices) {
  34149. var totalVertices = 0;
  34150. // Counting vertices
  34151. for (index = 0; index < meshes.length; index++) {
  34152. if (meshes[index]) {
  34153. totalVertices += meshes[index].getTotalVertices();
  34154. if (totalVertices > 65536) {
  34155. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34156. return null;
  34157. }
  34158. }
  34159. }
  34160. }
  34161. // Merge
  34162. var vertexData = null;
  34163. var otherVertexData;
  34164. var indiceArray = new Array();
  34165. var source = null;
  34166. for (index = 0; index < meshes.length; index++) {
  34167. if (meshes[index]) {
  34168. meshes[index].computeWorldMatrix(true);
  34169. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34170. otherVertexData.transform(meshes[index].getWorldMatrix());
  34171. if (vertexData) {
  34172. vertexData.merge(otherVertexData);
  34173. }
  34174. else {
  34175. vertexData = otherVertexData;
  34176. source = meshes[index];
  34177. }
  34178. if (subdivideWithSubMeshes) {
  34179. indiceArray.push(meshes[index].getTotalIndices());
  34180. }
  34181. }
  34182. }
  34183. source = source;
  34184. if (!meshSubclass) {
  34185. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34186. }
  34187. vertexData.applyToMesh(meshSubclass);
  34188. // Setting properties
  34189. meshSubclass.material = source.material;
  34190. meshSubclass.checkCollisions = source.checkCollisions;
  34191. // Cleaning
  34192. if (disposeSource) {
  34193. for (index = 0; index < meshes.length; index++) {
  34194. if (meshes[index]) {
  34195. meshes[index].dispose();
  34196. }
  34197. }
  34198. }
  34199. // Subdivide
  34200. if (subdivideWithSubMeshes) {
  34201. //-- removal of global submesh
  34202. meshSubclass.releaseSubMeshes();
  34203. index = 0;
  34204. var offset = 0;
  34205. //-- apply subdivision according to index table
  34206. while (index < indiceArray.length) {
  34207. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34208. offset += indiceArray[index];
  34209. index++;
  34210. }
  34211. }
  34212. return meshSubclass;
  34213. };
  34214. // Consts
  34215. Mesh._FRONTSIDE = 0;
  34216. Mesh._BACKSIDE = 1;
  34217. Mesh._DOUBLESIDE = 2;
  34218. Mesh._DEFAULTSIDE = 0;
  34219. Mesh._NO_CAP = 0;
  34220. Mesh._CAP_START = 1;
  34221. Mesh._CAP_END = 2;
  34222. Mesh._CAP_ALL = 3;
  34223. return Mesh;
  34224. }(BABYLON.AbstractMesh));
  34225. BABYLON.Mesh = Mesh;
  34226. })(BABYLON || (BABYLON = {}));
  34227. //# sourceMappingURL=babylon.mesh.js.map
  34228. var BABYLON;
  34229. (function (BABYLON) {
  34230. var BaseSubMesh = /** @class */ (function () {
  34231. function BaseSubMesh() {
  34232. }
  34233. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34234. get: function () {
  34235. return this._materialEffect;
  34236. },
  34237. enumerable: true,
  34238. configurable: true
  34239. });
  34240. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34241. if (defines === void 0) { defines = null; }
  34242. if (this._materialEffect === effect) {
  34243. if (!effect) {
  34244. this._materialDefines = null;
  34245. }
  34246. return;
  34247. }
  34248. this._materialDefines = defines;
  34249. this._materialEffect = effect;
  34250. };
  34251. return BaseSubMesh;
  34252. }());
  34253. BABYLON.BaseSubMesh = BaseSubMesh;
  34254. var SubMesh = /** @class */ (function (_super) {
  34255. __extends(SubMesh, _super);
  34256. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34257. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34258. var _this = _super.call(this) || this;
  34259. _this.materialIndex = materialIndex;
  34260. _this.verticesStart = verticesStart;
  34261. _this.verticesCount = verticesCount;
  34262. _this.indexStart = indexStart;
  34263. _this.indexCount = indexCount;
  34264. _this._renderId = 0;
  34265. _this._mesh = mesh;
  34266. _this._renderingMesh = renderingMesh || mesh;
  34267. mesh.subMeshes.push(_this);
  34268. _this._trianglePlanes = [];
  34269. _this._id = mesh.subMeshes.length - 1;
  34270. if (createBoundingBox) {
  34271. _this.refreshBoundingInfo();
  34272. mesh.computeWorldMatrix(true);
  34273. }
  34274. return _this;
  34275. }
  34276. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34277. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34278. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34279. };
  34280. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34281. get: function () {
  34282. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34283. },
  34284. enumerable: true,
  34285. configurable: true
  34286. });
  34287. /**
  34288. * Returns the submesh BoudingInfo object.
  34289. */
  34290. SubMesh.prototype.getBoundingInfo = function () {
  34291. if (this.IsGlobal) {
  34292. return this._mesh.getBoundingInfo();
  34293. }
  34294. return this._boundingInfo;
  34295. };
  34296. /**
  34297. * Sets the submesh BoundingInfo.
  34298. * Return the SubMesh.
  34299. */
  34300. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34301. this._boundingInfo = boundingInfo;
  34302. return this;
  34303. };
  34304. /**
  34305. * Returns the mesh of the current submesh.
  34306. */
  34307. SubMesh.prototype.getMesh = function () {
  34308. return this._mesh;
  34309. };
  34310. /**
  34311. * Returns the rendering mesh of the submesh.
  34312. */
  34313. SubMesh.prototype.getRenderingMesh = function () {
  34314. return this._renderingMesh;
  34315. };
  34316. /**
  34317. * Returns the submesh material.
  34318. */
  34319. SubMesh.prototype.getMaterial = function () {
  34320. var rootMaterial = this._renderingMesh.material;
  34321. if (rootMaterial === null || rootMaterial === undefined) {
  34322. return this._mesh.getScene().defaultMaterial;
  34323. }
  34324. else if (rootMaterial.getSubMaterial) {
  34325. var multiMaterial = rootMaterial;
  34326. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34327. if (this._currentMaterial !== effectiveMaterial) {
  34328. this._currentMaterial = effectiveMaterial;
  34329. this._materialDefines = null;
  34330. }
  34331. return effectiveMaterial;
  34332. }
  34333. return rootMaterial;
  34334. };
  34335. // Methods
  34336. /**
  34337. * Sets a new updated BoundingInfo object to the submesh.
  34338. * Returns the SubMesh.
  34339. */
  34340. SubMesh.prototype.refreshBoundingInfo = function () {
  34341. this._lastColliderWorldVertices = null;
  34342. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34343. return this;
  34344. }
  34345. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34346. if (!data) {
  34347. this._boundingInfo = this._mesh.getBoundingInfo();
  34348. return this;
  34349. }
  34350. var indices = this._renderingMesh.getIndices();
  34351. var extend;
  34352. //is this the only submesh?
  34353. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34354. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34355. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34356. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34357. }
  34358. else {
  34359. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34360. }
  34361. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34362. return this;
  34363. };
  34364. SubMesh.prototype._checkCollision = function (collider) {
  34365. var boundingInfo = this.getBoundingInfo();
  34366. return boundingInfo._checkCollision(collider);
  34367. };
  34368. /**
  34369. * Updates the submesh BoundingInfo.
  34370. * Returns the Submesh.
  34371. */
  34372. SubMesh.prototype.updateBoundingInfo = function (world) {
  34373. var boundingInfo = this.getBoundingInfo();
  34374. if (!boundingInfo) {
  34375. this.refreshBoundingInfo();
  34376. boundingInfo = this.getBoundingInfo();
  34377. }
  34378. boundingInfo.update(world);
  34379. return this;
  34380. };
  34381. /**
  34382. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34383. * Boolean returned.
  34384. */
  34385. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34386. var boundingInfo = this.getBoundingInfo();
  34387. if (!boundingInfo) {
  34388. return false;
  34389. }
  34390. return boundingInfo.isInFrustum(frustumPlanes);
  34391. };
  34392. /**
  34393. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34394. * Boolean returned.
  34395. */
  34396. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34397. var boundingInfo = this.getBoundingInfo();
  34398. if (!boundingInfo) {
  34399. return false;
  34400. }
  34401. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34402. };
  34403. /**
  34404. * Renders the submesh.
  34405. * Returns it.
  34406. */
  34407. SubMesh.prototype.render = function (enableAlphaMode) {
  34408. this._renderingMesh.render(this, enableAlphaMode);
  34409. return this;
  34410. };
  34411. /**
  34412. * Returns a new Index Buffer.
  34413. * Type returned : WebGLBuffer.
  34414. */
  34415. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34416. if (!this._linesIndexBuffer) {
  34417. var linesIndices = [];
  34418. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34419. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34420. }
  34421. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34422. this.linesIndexCount = linesIndices.length;
  34423. }
  34424. return this._linesIndexBuffer;
  34425. };
  34426. /**
  34427. * True is the passed Ray intersects the submesh bounding box.
  34428. * Boolean returned.
  34429. */
  34430. SubMesh.prototype.canIntersects = function (ray) {
  34431. var boundingInfo = this.getBoundingInfo();
  34432. if (!boundingInfo) {
  34433. return false;
  34434. }
  34435. return ray.intersectsBox(boundingInfo.boundingBox);
  34436. };
  34437. /**
  34438. * Returns an object IntersectionInfo.
  34439. */
  34440. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34441. var intersectInfo = null;
  34442. var material = this.getMaterial();
  34443. if (!material) {
  34444. return null;
  34445. }
  34446. switch (material.fillMode) {
  34447. case BABYLON.Material.PointListDrawMode:
  34448. case BABYLON.Material.LineListDrawMode:
  34449. case BABYLON.Material.LineLoopDrawMode:
  34450. case BABYLON.Material.LineStripDrawMode:
  34451. case BABYLON.Material.TriangleFanDrawMode:
  34452. case BABYLON.Material.TriangleStripDrawMode:
  34453. return null;
  34454. }
  34455. // LineMesh first as it's also a Mesh...
  34456. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34457. var lineMesh = this._mesh;
  34458. // Line test
  34459. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34460. var p0 = positions[indices[index]];
  34461. var p1 = positions[indices[index + 1]];
  34462. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34463. if (length < 0) {
  34464. continue;
  34465. }
  34466. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34467. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34468. if (fastCheck) {
  34469. break;
  34470. }
  34471. }
  34472. }
  34473. }
  34474. else {
  34475. // Triangles test
  34476. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34477. var p0 = positions[indices[index]];
  34478. var p1 = positions[indices[index + 1]];
  34479. var p2 = positions[indices[index + 2]];
  34480. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34481. if (currentIntersectInfo) {
  34482. if (currentIntersectInfo.distance < 0) {
  34483. continue;
  34484. }
  34485. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34486. intersectInfo = currentIntersectInfo;
  34487. intersectInfo.faceId = index / 3;
  34488. if (fastCheck) {
  34489. break;
  34490. }
  34491. }
  34492. }
  34493. }
  34494. }
  34495. return intersectInfo;
  34496. };
  34497. SubMesh.prototype._rebuild = function () {
  34498. if (this._linesIndexBuffer) {
  34499. this._linesIndexBuffer = null;
  34500. }
  34501. };
  34502. // Clone
  34503. /**
  34504. * Creates a new Submesh from the passed Mesh.
  34505. */
  34506. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34507. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34508. if (!this.IsGlobal) {
  34509. var boundingInfo = this.getBoundingInfo();
  34510. if (!boundingInfo) {
  34511. return result;
  34512. }
  34513. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34514. }
  34515. return result;
  34516. };
  34517. // Dispose
  34518. /**
  34519. * Disposes the Submesh.
  34520. * Returns nothing.
  34521. */
  34522. SubMesh.prototype.dispose = function () {
  34523. if (this._linesIndexBuffer) {
  34524. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34525. this._linesIndexBuffer = null;
  34526. }
  34527. // Remove from mesh
  34528. var index = this._mesh.subMeshes.indexOf(this);
  34529. this._mesh.subMeshes.splice(index, 1);
  34530. };
  34531. // Statics
  34532. /**
  34533. * Creates a new Submesh from the passed parameters :
  34534. * - materialIndex (integer) : the index of the main mesh material.
  34535. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34536. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34537. * - mesh (Mesh) : the main mesh to create the submesh from.
  34538. * - renderingMesh (optional Mesh) : rendering mesh.
  34539. */
  34540. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34541. var minVertexIndex = Number.MAX_VALUE;
  34542. var maxVertexIndex = -Number.MAX_VALUE;
  34543. renderingMesh = (renderingMesh || mesh);
  34544. var indices = renderingMesh.getIndices();
  34545. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34546. var vertexIndex = indices[index];
  34547. if (vertexIndex < minVertexIndex)
  34548. minVertexIndex = vertexIndex;
  34549. if (vertexIndex > maxVertexIndex)
  34550. maxVertexIndex = vertexIndex;
  34551. }
  34552. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34553. };
  34554. return SubMesh;
  34555. }(BaseSubMesh));
  34556. BABYLON.SubMesh = SubMesh;
  34557. })(BABYLON || (BABYLON = {}));
  34558. //# sourceMappingURL=babylon.subMesh.js.map
  34559. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34560. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34561. s = arguments[i];
  34562. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34563. t[p] = s[p];
  34564. }
  34565. return t;
  34566. };
  34567. var BABYLON;
  34568. (function (BABYLON) {
  34569. /**
  34570. * Manages the defines for the Material
  34571. */
  34572. var MaterialDefines = /** @class */ (function () {
  34573. function MaterialDefines() {
  34574. this._isDirty = true;
  34575. /** @hidden */
  34576. this._areLightsDirty = true;
  34577. /** @hidden */
  34578. this._areAttributesDirty = true;
  34579. /** @hidden */
  34580. this._areTexturesDirty = true;
  34581. /** @hidden */
  34582. this._areFresnelDirty = true;
  34583. /** @hidden */
  34584. this._areMiscDirty = true;
  34585. /** @hidden */
  34586. this._areImageProcessingDirty = true;
  34587. /** @hidden */
  34588. this._normals = false;
  34589. /** @hidden */
  34590. this._uvs = false;
  34591. /** @hidden */
  34592. this._needNormals = false;
  34593. /** @hidden */
  34594. this._needUVs = false;
  34595. }
  34596. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34597. /**
  34598. * Specifies if the material needs to be re-calculated
  34599. */
  34600. get: function () {
  34601. return this._isDirty;
  34602. },
  34603. enumerable: true,
  34604. configurable: true
  34605. });
  34606. /**
  34607. * Marks the material to indicate that it has been re-calculated
  34608. */
  34609. MaterialDefines.prototype.markAsProcessed = function () {
  34610. this._isDirty = false;
  34611. this._areAttributesDirty = false;
  34612. this._areTexturesDirty = false;
  34613. this._areFresnelDirty = false;
  34614. this._areLightsDirty = false;
  34615. this._areMiscDirty = false;
  34616. this._areImageProcessingDirty = false;
  34617. };
  34618. /**
  34619. * Marks the material to indicate that it needs to be re-calculated
  34620. */
  34621. MaterialDefines.prototype.markAsUnprocessed = function () {
  34622. this._isDirty = true;
  34623. };
  34624. /**
  34625. * Marks the material to indicate all of its defines need to be re-calculated
  34626. */
  34627. MaterialDefines.prototype.markAllAsDirty = function () {
  34628. this._areTexturesDirty = true;
  34629. this._areAttributesDirty = true;
  34630. this._areLightsDirty = true;
  34631. this._areFresnelDirty = true;
  34632. this._areMiscDirty = true;
  34633. this._areImageProcessingDirty = true;
  34634. this._isDirty = true;
  34635. };
  34636. /**
  34637. * Marks the material to indicate that image processing needs to be re-calculated
  34638. */
  34639. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34640. this._areImageProcessingDirty = true;
  34641. this._isDirty = true;
  34642. };
  34643. /**
  34644. * Marks the material to indicate the lights need to be re-calculated
  34645. */
  34646. MaterialDefines.prototype.markAsLightDirty = function () {
  34647. this._areLightsDirty = true;
  34648. this._isDirty = true;
  34649. };
  34650. /**
  34651. * Marks the attribute state as changed
  34652. */
  34653. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34654. this._areAttributesDirty = true;
  34655. this._isDirty = true;
  34656. };
  34657. /**
  34658. * Marks the texture state as changed
  34659. */
  34660. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34661. this._areTexturesDirty = true;
  34662. this._isDirty = true;
  34663. };
  34664. /**
  34665. * Marks the fresnel state as changed
  34666. */
  34667. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34668. this._areFresnelDirty = true;
  34669. this._isDirty = true;
  34670. };
  34671. /**
  34672. * Marks the misc state as changed
  34673. */
  34674. MaterialDefines.prototype.markAsMiscDirty = function () {
  34675. this._areMiscDirty = true;
  34676. this._isDirty = true;
  34677. };
  34678. /**
  34679. * Rebuilds the material defines
  34680. */
  34681. MaterialDefines.prototype.rebuild = function () {
  34682. if (this._keys) {
  34683. delete this._keys;
  34684. }
  34685. this._keys = [];
  34686. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34687. var key = _a[_i];
  34688. if (key[0] === "_") {
  34689. continue;
  34690. }
  34691. this._keys.push(key);
  34692. }
  34693. };
  34694. /**
  34695. * Specifies if two material defines are equal
  34696. * @param other - A material define instance to compare to
  34697. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34698. */
  34699. MaterialDefines.prototype.isEqual = function (other) {
  34700. if (this._keys.length !== other._keys.length) {
  34701. return false;
  34702. }
  34703. for (var index = 0; index < this._keys.length; index++) {
  34704. var prop = this._keys[index];
  34705. if (this[prop] !== other[prop]) {
  34706. return false;
  34707. }
  34708. }
  34709. return true;
  34710. };
  34711. /**
  34712. * Clones this instance's defines to another instance
  34713. * @param other - material defines to clone values to
  34714. */
  34715. MaterialDefines.prototype.cloneTo = function (other) {
  34716. if (this._keys.length !== other._keys.length) {
  34717. other._keys = this._keys.slice(0);
  34718. }
  34719. for (var index = 0; index < this._keys.length; index++) {
  34720. var prop = this._keys[index];
  34721. other[prop] = this[prop];
  34722. }
  34723. };
  34724. /**
  34725. * Resets the material define values
  34726. */
  34727. MaterialDefines.prototype.reset = function () {
  34728. for (var index = 0; index < this._keys.length; index++) {
  34729. var prop = this._keys[index];
  34730. var type = typeof this[prop];
  34731. switch (type) {
  34732. case "number":
  34733. this[prop] = 0;
  34734. break;
  34735. case "string":
  34736. this[prop] = "";
  34737. break;
  34738. default:
  34739. this[prop] = false;
  34740. break;
  34741. }
  34742. }
  34743. };
  34744. /**
  34745. * Converts the material define values to a string
  34746. * @returns - String of material define information
  34747. */
  34748. MaterialDefines.prototype.toString = function () {
  34749. var result = "";
  34750. for (var index = 0; index < this._keys.length; index++) {
  34751. var prop = this._keys[index];
  34752. var value = this[prop];
  34753. var type = typeof value;
  34754. switch (type) {
  34755. case "number":
  34756. case "string":
  34757. result += "#define " + prop + " " + value + "\n";
  34758. break;
  34759. default:
  34760. if (value) {
  34761. result += "#define " + prop + "\n";
  34762. }
  34763. break;
  34764. }
  34765. }
  34766. return result;
  34767. };
  34768. return MaterialDefines;
  34769. }());
  34770. BABYLON.MaterialDefines = MaterialDefines;
  34771. /**
  34772. * Base class for the main features of a material in Babylon.js
  34773. */
  34774. var Material = /** @class */ (function () {
  34775. /**
  34776. * Creates a material instance
  34777. * @param name defines the name of the material
  34778. * @param scene defines the scene to reference
  34779. * @param doNotAdd specifies if the material should be added to the scene
  34780. */
  34781. function Material(name, scene, doNotAdd) {
  34782. /**
  34783. * Specifies if the ready state should be checked on each call
  34784. */
  34785. this.checkReadyOnEveryCall = false;
  34786. /**
  34787. * Specifies if the ready state should be checked once
  34788. */
  34789. this.checkReadyOnlyOnce = false;
  34790. /**
  34791. * The state of the material
  34792. */
  34793. this.state = "";
  34794. /**
  34795. * The alpha value of the material
  34796. */
  34797. this._alpha = 1.0;
  34798. /**
  34799. * Specifies if back face culling is enabled
  34800. */
  34801. this._backFaceCulling = true;
  34802. /**
  34803. * Specifies if the material should be serialized
  34804. */
  34805. this.doNotSerialize = false;
  34806. /**
  34807. * Specifies if the effect should be stored on sub meshes
  34808. */
  34809. this.storeEffectOnSubMeshes = false;
  34810. /**
  34811. * An event triggered when the material is disposed
  34812. */
  34813. this.onDisposeObservable = new BABYLON.Observable();
  34814. /**
  34815. * An event triggered when the material is bound
  34816. */
  34817. this.onBindObservable = new BABYLON.Observable();
  34818. /**
  34819. * An event triggered when the material is unbound
  34820. */
  34821. this.onUnBindObservable = new BABYLON.Observable();
  34822. /**
  34823. * Stores the value of the alpha mode
  34824. */
  34825. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34826. /**
  34827. * Stores the state of the need depth pre-pass value
  34828. */
  34829. this._needDepthPrePass = false;
  34830. /**
  34831. * Specifies if depth writing should be disabled
  34832. */
  34833. this.disableDepthWrite = false;
  34834. /**
  34835. * Specifies if depth writing should be forced
  34836. */
  34837. this.forceDepthWrite = false;
  34838. /**
  34839. * Specifies if there should be a separate pass for culling
  34840. */
  34841. this.separateCullingPass = false;
  34842. /**
  34843. * Stores the state specifing if fog should be enabled
  34844. */
  34845. this._fogEnabled = true;
  34846. /**
  34847. * Stores the size of points
  34848. */
  34849. this.pointSize = 1.0;
  34850. /**
  34851. * Stores the z offset value
  34852. */
  34853. this.zOffset = 0;
  34854. /**
  34855. * Specifies if the material was previously ready
  34856. */
  34857. this._wasPreviouslyReady = false;
  34858. /**
  34859. * Stores the fill mode state
  34860. */
  34861. this._fillMode = Material.TriangleFillMode;
  34862. this.name = name;
  34863. this.id = name || BABYLON.Tools.RandomId();
  34864. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34865. this.uniqueId = this._scene.getUniqueId();
  34866. if (this._scene.useRightHandedSystem) {
  34867. this.sideOrientation = Material.ClockWiseSideOrientation;
  34868. }
  34869. else {
  34870. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34871. }
  34872. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34873. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34874. if (!doNotAdd) {
  34875. this._scene.materials.push(this);
  34876. }
  34877. }
  34878. Object.defineProperty(Material, "TriangleFillMode", {
  34879. /**
  34880. * Returns the triangle fill mode
  34881. */
  34882. get: function () {
  34883. return Material._TriangleFillMode;
  34884. },
  34885. enumerable: true,
  34886. configurable: true
  34887. });
  34888. Object.defineProperty(Material, "WireFrameFillMode", {
  34889. /**
  34890. * Returns the wireframe mode
  34891. */
  34892. get: function () {
  34893. return Material._WireFrameFillMode;
  34894. },
  34895. enumerable: true,
  34896. configurable: true
  34897. });
  34898. Object.defineProperty(Material, "PointFillMode", {
  34899. /**
  34900. * Returns the point fill mode
  34901. */
  34902. get: function () {
  34903. return Material._PointFillMode;
  34904. },
  34905. enumerable: true,
  34906. configurable: true
  34907. });
  34908. Object.defineProperty(Material, "PointListDrawMode", {
  34909. /**
  34910. * Returns the point list draw mode
  34911. */
  34912. get: function () {
  34913. return Material._PointListDrawMode;
  34914. },
  34915. enumerable: true,
  34916. configurable: true
  34917. });
  34918. Object.defineProperty(Material, "LineListDrawMode", {
  34919. /**
  34920. * Returns the line list draw mode
  34921. */
  34922. get: function () {
  34923. return Material._LineListDrawMode;
  34924. },
  34925. enumerable: true,
  34926. configurable: true
  34927. });
  34928. Object.defineProperty(Material, "LineLoopDrawMode", {
  34929. /**
  34930. * Returns the line loop draw mode
  34931. */
  34932. get: function () {
  34933. return Material._LineLoopDrawMode;
  34934. },
  34935. enumerable: true,
  34936. configurable: true
  34937. });
  34938. Object.defineProperty(Material, "LineStripDrawMode", {
  34939. /**
  34940. * Returns the line strip draw mode
  34941. */
  34942. get: function () {
  34943. return Material._LineStripDrawMode;
  34944. },
  34945. enumerable: true,
  34946. configurable: true
  34947. });
  34948. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34949. /**
  34950. * Returns the triangle strip draw mode
  34951. */
  34952. get: function () {
  34953. return Material._TriangleStripDrawMode;
  34954. },
  34955. enumerable: true,
  34956. configurable: true
  34957. });
  34958. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34959. /**
  34960. * Returns the triangle fan draw mode
  34961. */
  34962. get: function () {
  34963. return Material._TriangleFanDrawMode;
  34964. },
  34965. enumerable: true,
  34966. configurable: true
  34967. });
  34968. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34969. /**
  34970. * Returns the clock-wise side orientation
  34971. */
  34972. get: function () {
  34973. return Material._ClockWiseSideOrientation;
  34974. },
  34975. enumerable: true,
  34976. configurable: true
  34977. });
  34978. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34979. /**
  34980. * Returns the counter clock-wise side orientation
  34981. */
  34982. get: function () {
  34983. return Material._CounterClockWiseSideOrientation;
  34984. },
  34985. enumerable: true,
  34986. configurable: true
  34987. });
  34988. Object.defineProperty(Material, "TextureDirtyFlag", {
  34989. /**
  34990. * Returns the dirty texture flag value
  34991. */
  34992. get: function () {
  34993. return Material._TextureDirtyFlag;
  34994. },
  34995. enumerable: true,
  34996. configurable: true
  34997. });
  34998. Object.defineProperty(Material, "LightDirtyFlag", {
  34999. /**
  35000. * Returns the dirty light flag value
  35001. */
  35002. get: function () {
  35003. return Material._LightDirtyFlag;
  35004. },
  35005. enumerable: true,
  35006. configurable: true
  35007. });
  35008. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35009. /**
  35010. * Returns the dirty fresnel flag value
  35011. */
  35012. get: function () {
  35013. return Material._FresnelDirtyFlag;
  35014. },
  35015. enumerable: true,
  35016. configurable: true
  35017. });
  35018. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35019. /**
  35020. * Returns the dirty attributes flag value
  35021. */
  35022. get: function () {
  35023. return Material._AttributesDirtyFlag;
  35024. },
  35025. enumerable: true,
  35026. configurable: true
  35027. });
  35028. Object.defineProperty(Material, "MiscDirtyFlag", {
  35029. /**
  35030. * Returns the dirty misc flag value
  35031. */
  35032. get: function () {
  35033. return Material._MiscDirtyFlag;
  35034. },
  35035. enumerable: true,
  35036. configurable: true
  35037. });
  35038. Object.defineProperty(Material.prototype, "alpha", {
  35039. /**
  35040. * Gets the alpha value of the material
  35041. */
  35042. get: function () {
  35043. return this._alpha;
  35044. },
  35045. /**
  35046. * Sets the alpha value of the material
  35047. */
  35048. set: function (value) {
  35049. if (this._alpha === value) {
  35050. return;
  35051. }
  35052. this._alpha = value;
  35053. this.markAsDirty(Material.MiscDirtyFlag);
  35054. },
  35055. enumerable: true,
  35056. configurable: true
  35057. });
  35058. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35059. /**
  35060. * Gets the back-face culling state
  35061. */
  35062. get: function () {
  35063. return this._backFaceCulling;
  35064. },
  35065. /**
  35066. * Sets the back-face culling state
  35067. */
  35068. set: function (value) {
  35069. if (this._backFaceCulling === value) {
  35070. return;
  35071. }
  35072. this._backFaceCulling = value;
  35073. this.markAsDirty(Material.TextureDirtyFlag);
  35074. },
  35075. enumerable: true,
  35076. configurable: true
  35077. });
  35078. Object.defineProperty(Material.prototype, "onDispose", {
  35079. /**
  35080. * Called during a dispose event
  35081. */
  35082. set: function (callback) {
  35083. if (this._onDisposeObserver) {
  35084. this.onDisposeObservable.remove(this._onDisposeObserver);
  35085. }
  35086. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35087. },
  35088. enumerable: true,
  35089. configurable: true
  35090. });
  35091. Object.defineProperty(Material.prototype, "onBind", {
  35092. /**
  35093. * Called during a bind event
  35094. */
  35095. set: function (callback) {
  35096. if (this._onBindObserver) {
  35097. this.onBindObservable.remove(this._onBindObserver);
  35098. }
  35099. this._onBindObserver = this.onBindObservable.add(callback);
  35100. },
  35101. enumerable: true,
  35102. configurable: true
  35103. });
  35104. Object.defineProperty(Material.prototype, "alphaMode", {
  35105. /**
  35106. * Gets the value of the alpha mode
  35107. */
  35108. get: function () {
  35109. return this._alphaMode;
  35110. },
  35111. /**
  35112. * Sets the value of the alpha mode.
  35113. *
  35114. * | Value | Type | Description |
  35115. * | --- | --- | --- |
  35116. * | 0 | ALPHA_DISABLE | |
  35117. * | 1 | ALPHA_ADD | |
  35118. * | 2 | ALPHA_COMBINE | |
  35119. * | 3 | ALPHA_SUBTRACT | |
  35120. * | 4 | ALPHA_MULTIPLY | |
  35121. * | 5 | ALPHA_MAXIMIZED | |
  35122. * | 6 | ALPHA_ONEONE | |
  35123. * | 7 | ALPHA_PREMULTIPLIED | |
  35124. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35125. * | 9 | ALPHA_INTERPOLATE | |
  35126. * | 10 | ALPHA_SCREENMODE | |
  35127. *
  35128. */
  35129. set: function (value) {
  35130. if (this._alphaMode === value) {
  35131. return;
  35132. }
  35133. this._alphaMode = value;
  35134. this.markAsDirty(Material.TextureDirtyFlag);
  35135. },
  35136. enumerable: true,
  35137. configurable: true
  35138. });
  35139. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35140. /**
  35141. * Gets the depth pre-pass value
  35142. */
  35143. get: function () {
  35144. return this._needDepthPrePass;
  35145. },
  35146. /**
  35147. * Sets the need depth pre-pass value
  35148. */
  35149. set: function (value) {
  35150. if (this._needDepthPrePass === value) {
  35151. return;
  35152. }
  35153. this._needDepthPrePass = value;
  35154. if (this._needDepthPrePass) {
  35155. this.checkReadyOnEveryCall = true;
  35156. }
  35157. },
  35158. enumerable: true,
  35159. configurable: true
  35160. });
  35161. Object.defineProperty(Material.prototype, "fogEnabled", {
  35162. /**
  35163. * Gets the value of the fog enabled state
  35164. */
  35165. get: function () {
  35166. return this._fogEnabled;
  35167. },
  35168. /**
  35169. * Sets the state for enabling fog
  35170. */
  35171. set: function (value) {
  35172. if (this._fogEnabled === value) {
  35173. return;
  35174. }
  35175. this._fogEnabled = value;
  35176. this.markAsDirty(Material.MiscDirtyFlag);
  35177. },
  35178. enumerable: true,
  35179. configurable: true
  35180. });
  35181. Object.defineProperty(Material.prototype, "wireframe", {
  35182. /**
  35183. * Gets a value specifying if wireframe mode is enabled
  35184. */
  35185. get: function () {
  35186. switch (this._fillMode) {
  35187. case Material.WireFrameFillMode:
  35188. case Material.LineListDrawMode:
  35189. case Material.LineLoopDrawMode:
  35190. case Material.LineStripDrawMode:
  35191. return true;
  35192. }
  35193. return this._scene.forceWireframe;
  35194. },
  35195. /**
  35196. * Sets the state of wireframe mode
  35197. */
  35198. set: function (value) {
  35199. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35200. },
  35201. enumerable: true,
  35202. configurable: true
  35203. });
  35204. Object.defineProperty(Material.prototype, "pointsCloud", {
  35205. /**
  35206. * Gets the value specifying if point clouds are enabled
  35207. */
  35208. get: function () {
  35209. switch (this._fillMode) {
  35210. case Material.PointFillMode:
  35211. case Material.PointListDrawMode:
  35212. return true;
  35213. }
  35214. return this._scene.forcePointsCloud;
  35215. },
  35216. /**
  35217. * Sets the state of point cloud mode
  35218. */
  35219. set: function (value) {
  35220. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35221. },
  35222. enumerable: true,
  35223. configurable: true
  35224. });
  35225. Object.defineProperty(Material.prototype, "fillMode", {
  35226. /**
  35227. * Gets the material fill mode
  35228. */
  35229. get: function () {
  35230. return this._fillMode;
  35231. },
  35232. /**
  35233. * Sets the material fill mode
  35234. */
  35235. set: function (value) {
  35236. if (this._fillMode === value) {
  35237. return;
  35238. }
  35239. this._fillMode = value;
  35240. this.markAsDirty(Material.MiscDirtyFlag);
  35241. },
  35242. enumerable: true,
  35243. configurable: true
  35244. });
  35245. /**
  35246. * Returns a string representation of the current material
  35247. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35248. * @returns a string with material information
  35249. */
  35250. Material.prototype.toString = function (fullDetails) {
  35251. var ret = "Name: " + this.name;
  35252. if (fullDetails) {
  35253. }
  35254. return ret;
  35255. };
  35256. /**
  35257. * Gets the class name of the material
  35258. * @returns a string with the class name of the material
  35259. */
  35260. Material.prototype.getClassName = function () {
  35261. return "Material";
  35262. };
  35263. Object.defineProperty(Material.prototype, "isFrozen", {
  35264. /**
  35265. * Specifies if updates for the material been locked
  35266. */
  35267. get: function () {
  35268. return this.checkReadyOnlyOnce;
  35269. },
  35270. enumerable: true,
  35271. configurable: true
  35272. });
  35273. /**
  35274. * Locks updates for the material
  35275. */
  35276. Material.prototype.freeze = function () {
  35277. this.checkReadyOnlyOnce = true;
  35278. };
  35279. /**
  35280. * Unlocks updates for the material
  35281. */
  35282. Material.prototype.unfreeze = function () {
  35283. this.checkReadyOnlyOnce = false;
  35284. };
  35285. /**
  35286. * Specifies if the material is ready to be used
  35287. * @param mesh defines the mesh to check
  35288. * @param useInstances specifies if instances should be used
  35289. * @returns a boolean indicating if the material is ready to be used
  35290. */
  35291. Material.prototype.isReady = function (mesh, useInstances) {
  35292. return true;
  35293. };
  35294. /**
  35295. * Specifies that the submesh is ready to be used
  35296. * @param mesh defines the mesh to check
  35297. * @param subMesh defines which submesh to check
  35298. * @param useInstances specifies that instances should be used
  35299. * @returns a boolean indicating that the submesh is ready or not
  35300. */
  35301. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35302. return false;
  35303. };
  35304. /**
  35305. * Returns the material effect
  35306. * @returns the effect associated with the material
  35307. */
  35308. Material.prototype.getEffect = function () {
  35309. return this._effect;
  35310. };
  35311. /**
  35312. * Returns the current scene
  35313. * @returns a Scene
  35314. */
  35315. Material.prototype.getScene = function () {
  35316. return this._scene;
  35317. };
  35318. /**
  35319. * Specifies if the material will require alpha blending
  35320. * @returns a boolean specifying if alpha blending is needed
  35321. */
  35322. Material.prototype.needAlphaBlending = function () {
  35323. return (this.alpha < 1.0);
  35324. };
  35325. /**
  35326. * Specifies if the mesh will require alpha blending
  35327. * @param mesh defines the mesh to check
  35328. * @returns a boolean specifying if alpha blending is needed for the mesh
  35329. */
  35330. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35331. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35332. };
  35333. /**
  35334. * Specifies if this material should be rendered in alpha test mode
  35335. * @returns a boolean specifying if an alpha test is needed.
  35336. */
  35337. Material.prototype.needAlphaTesting = function () {
  35338. return false;
  35339. };
  35340. /**
  35341. * Gets the texture used for the alpha test
  35342. * @returns the texture to use for alpha testing
  35343. */
  35344. Material.prototype.getAlphaTestTexture = function () {
  35345. return null;
  35346. };
  35347. /**
  35348. * Marks the material to indicate that it needs to be re-calculated
  35349. */
  35350. Material.prototype.markDirty = function () {
  35351. this._wasPreviouslyReady = false;
  35352. };
  35353. /** @hidden */
  35354. Material.prototype._preBind = function (effect, overrideOrientation) {
  35355. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35356. var engine = this._scene.getEngine();
  35357. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35358. var reverse = orientation === Material.ClockWiseSideOrientation;
  35359. engine.enableEffect(effect ? effect : this._effect);
  35360. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35361. return reverse;
  35362. };
  35363. /**
  35364. * Binds the material to the mesh
  35365. * @param world defines the world transformation matrix
  35366. * @param mesh defines the mesh to bind the material to
  35367. */
  35368. Material.prototype.bind = function (world, mesh) {
  35369. };
  35370. /**
  35371. * Binds the submesh to the material
  35372. * @param world defines the world transformation matrix
  35373. * @param mesh defines the mesh containing the submesh
  35374. * @param subMesh defines the submesh to bind the material to
  35375. */
  35376. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35377. };
  35378. /**
  35379. * Binds the world matrix to the material
  35380. * @param world defines the world transformation matrix
  35381. */
  35382. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35383. };
  35384. /**
  35385. * Binds the scene's uniform buffer to the effect.
  35386. * @param effect defines the effect to bind to the scene uniform buffer
  35387. * @param sceneUbo defines the uniform buffer storing scene data
  35388. */
  35389. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35390. sceneUbo.bindToEffect(effect, "Scene");
  35391. };
  35392. /**
  35393. * Binds the view matrix to the effect
  35394. * @param effect defines the effect to bind the view matrix to
  35395. */
  35396. Material.prototype.bindView = function (effect) {
  35397. if (!this._useUBO) {
  35398. effect.setMatrix("view", this.getScene().getViewMatrix());
  35399. }
  35400. else {
  35401. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35402. }
  35403. };
  35404. /**
  35405. * Binds the view projection matrix to the effect
  35406. * @param effect defines the effect to bind the view projection matrix to
  35407. */
  35408. Material.prototype.bindViewProjection = function (effect) {
  35409. if (!this._useUBO) {
  35410. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35411. }
  35412. else {
  35413. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35414. }
  35415. };
  35416. /**
  35417. * Specifies if material alpha testing should be turned on for the mesh
  35418. * @param mesh defines the mesh to check
  35419. */
  35420. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35421. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35422. };
  35423. /**
  35424. * Processes to execute after binding the material to a mesh
  35425. * @param mesh defines the rendered mesh
  35426. */
  35427. Material.prototype._afterBind = function (mesh) {
  35428. this._scene._cachedMaterial = this;
  35429. if (mesh) {
  35430. this._scene._cachedVisibility = mesh.visibility;
  35431. }
  35432. else {
  35433. this._scene._cachedVisibility = 1;
  35434. }
  35435. if (mesh) {
  35436. this.onBindObservable.notifyObservers(mesh);
  35437. }
  35438. if (this.disableDepthWrite) {
  35439. var engine = this._scene.getEngine();
  35440. this._cachedDepthWriteState = engine.getDepthWrite();
  35441. engine.setDepthWrite(false);
  35442. }
  35443. };
  35444. /**
  35445. * Unbinds the material from the mesh
  35446. */
  35447. Material.prototype.unbind = function () {
  35448. this.onUnBindObservable.notifyObservers(this);
  35449. if (this.disableDepthWrite) {
  35450. var engine = this._scene.getEngine();
  35451. engine.setDepthWrite(this._cachedDepthWriteState);
  35452. }
  35453. };
  35454. /**
  35455. * Gets the active textures from the material
  35456. * @returns an array of textures
  35457. */
  35458. Material.prototype.getActiveTextures = function () {
  35459. return [];
  35460. };
  35461. /**
  35462. * Specifies if the material uses a texture
  35463. * @param texture defines the texture to check against the material
  35464. * @returns a boolean specifying if the material uses the texture
  35465. */
  35466. Material.prototype.hasTexture = function (texture) {
  35467. return false;
  35468. };
  35469. /**
  35470. * Makes a duplicate of the material, and gives it a new name
  35471. * @param name defines the new name for the duplicated material
  35472. * @returns the cloned material
  35473. */
  35474. Material.prototype.clone = function (name) {
  35475. return null;
  35476. };
  35477. /**
  35478. * Gets the meshes bound to the material
  35479. * @returns an array of meshes bound to the material
  35480. */
  35481. Material.prototype.getBindedMeshes = function () {
  35482. var result = new Array();
  35483. for (var index = 0; index < this._scene.meshes.length; index++) {
  35484. var mesh = this._scene.meshes[index];
  35485. if (mesh.material === this) {
  35486. result.push(mesh);
  35487. }
  35488. }
  35489. return result;
  35490. };
  35491. /**
  35492. * Force shader compilation
  35493. * @param mesh defines the mesh associated with this material
  35494. * @param onCompiled defines a function to execute once the material is compiled
  35495. * @param options defines the options to configure the compilation
  35496. */
  35497. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35498. var _this = this;
  35499. var localOptions = __assign({ clipPlane: false }, options);
  35500. var subMesh = new BABYLON.BaseSubMesh();
  35501. var scene = this.getScene();
  35502. var checkReady = function () {
  35503. if (!_this._scene || !_this._scene.getEngine()) {
  35504. return;
  35505. }
  35506. if (subMesh._materialDefines) {
  35507. subMesh._materialDefines._renderId = -1;
  35508. }
  35509. var clipPlaneState = scene.clipPlane;
  35510. if (localOptions.clipPlane) {
  35511. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35512. }
  35513. if (_this.storeEffectOnSubMeshes) {
  35514. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35515. if (onCompiled) {
  35516. onCompiled(_this);
  35517. }
  35518. }
  35519. else {
  35520. setTimeout(checkReady, 16);
  35521. }
  35522. }
  35523. else {
  35524. if (_this.isReady(mesh)) {
  35525. if (onCompiled) {
  35526. onCompiled(_this);
  35527. }
  35528. }
  35529. else {
  35530. setTimeout(checkReady, 16);
  35531. }
  35532. }
  35533. if (localOptions.clipPlane) {
  35534. scene.clipPlane = clipPlaneState;
  35535. }
  35536. };
  35537. checkReady();
  35538. };
  35539. /**
  35540. * Force shader compilation
  35541. * @param mesh defines the mesh that will use this material
  35542. * @param options defines additional options for compiling the shaders
  35543. * @returns a promise that resolves when the compilation completes
  35544. */
  35545. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35546. var _this = this;
  35547. return new Promise(function (resolve) {
  35548. _this.forceCompilation(mesh, function () {
  35549. resolve();
  35550. }, options);
  35551. });
  35552. };
  35553. /**
  35554. * Marks a define in the material to indicate that it needs to be re-computed
  35555. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35556. */
  35557. Material.prototype.markAsDirty = function (flag) {
  35558. if (flag & Material.TextureDirtyFlag) {
  35559. this._markAllSubMeshesAsTexturesDirty();
  35560. }
  35561. if (flag & Material.LightDirtyFlag) {
  35562. this._markAllSubMeshesAsLightsDirty();
  35563. }
  35564. if (flag & Material.FresnelDirtyFlag) {
  35565. this._markAllSubMeshesAsFresnelDirty();
  35566. }
  35567. if (flag & Material.AttributesDirtyFlag) {
  35568. this._markAllSubMeshesAsAttributesDirty();
  35569. }
  35570. if (flag & Material.MiscDirtyFlag) {
  35571. this._markAllSubMeshesAsMiscDirty();
  35572. }
  35573. this.getScene().resetCachedMaterial();
  35574. };
  35575. /**
  35576. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35577. * @param func defines a function which checks material defines against the submeshes
  35578. */
  35579. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35580. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35581. var mesh = _a[_i];
  35582. if (!mesh.subMeshes) {
  35583. continue;
  35584. }
  35585. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35586. var subMesh = _c[_b];
  35587. if (subMesh.getMaterial() !== this) {
  35588. continue;
  35589. }
  35590. if (!subMesh._materialDefines) {
  35591. continue;
  35592. }
  35593. func(subMesh._materialDefines);
  35594. }
  35595. }
  35596. };
  35597. /**
  35598. * Indicates that image processing needs to be re-calculated for all submeshes
  35599. */
  35600. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35601. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35602. };
  35603. /**
  35604. * Indicates that textures need to be re-calculated for all submeshes
  35605. */
  35606. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35607. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35608. };
  35609. /**
  35610. * Indicates that fresnel needs to be re-calculated for all submeshes
  35611. */
  35612. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35613. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35614. };
  35615. /**
  35616. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35617. */
  35618. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35619. this._markAllSubMeshesAsDirty(function (defines) {
  35620. defines.markAsFresnelDirty();
  35621. defines.markAsMiscDirty();
  35622. });
  35623. };
  35624. /**
  35625. * Indicates that lights need to be re-calculated for all submeshes
  35626. */
  35627. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35628. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35629. };
  35630. /**
  35631. * Indicates that attributes need to be re-calculated for all submeshes
  35632. */
  35633. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35634. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35635. };
  35636. /**
  35637. * Indicates that misc needs to be re-calculated for all submeshes
  35638. */
  35639. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35640. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35641. };
  35642. /**
  35643. * Indicates that textures and misc need to be re-calculated for all submeshes
  35644. */
  35645. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35646. this._markAllSubMeshesAsDirty(function (defines) {
  35647. defines.markAsTexturesDirty();
  35648. defines.markAsMiscDirty();
  35649. });
  35650. };
  35651. /**
  35652. * Disposes the material
  35653. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35654. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35655. */
  35656. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35657. // Animations
  35658. this.getScene().stopAnimation(this);
  35659. this.getScene().freeProcessedMaterials();
  35660. // Remove from scene
  35661. var index = this._scene.materials.indexOf(this);
  35662. if (index >= 0) {
  35663. this._scene.materials.splice(index, 1);
  35664. }
  35665. // Remove from meshes
  35666. for (index = 0; index < this._scene.meshes.length; index++) {
  35667. var mesh = this._scene.meshes[index];
  35668. if (mesh.material === this) {
  35669. mesh.material = null;
  35670. if (mesh.geometry) {
  35671. var geometry = (mesh.geometry);
  35672. if (this.storeEffectOnSubMeshes) {
  35673. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35674. var subMesh = _a[_i];
  35675. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35676. if (forceDisposeEffect && subMesh._materialEffect) {
  35677. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35678. }
  35679. }
  35680. }
  35681. else {
  35682. geometry._releaseVertexArrayObject(this._effect);
  35683. }
  35684. }
  35685. }
  35686. }
  35687. this._uniformBuffer.dispose();
  35688. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35689. if (forceDisposeEffect && this._effect) {
  35690. if (!this.storeEffectOnSubMeshes) {
  35691. this._scene.getEngine()._releaseEffect(this._effect);
  35692. }
  35693. this._effect = null;
  35694. }
  35695. // Callback
  35696. this.onDisposeObservable.notifyObservers(this);
  35697. this.onDisposeObservable.clear();
  35698. this.onBindObservable.clear();
  35699. this.onUnBindObservable.clear();
  35700. };
  35701. /**
  35702. * Serializes this material
  35703. * @returns the serialized material object
  35704. */
  35705. Material.prototype.serialize = function () {
  35706. return BABYLON.SerializationHelper.Serialize(this);
  35707. };
  35708. /**
  35709. * Creates a MultiMaterial from parsed MultiMaterial data.
  35710. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35711. * @param scene defines the hosting scene
  35712. * @returns a new MultiMaterial
  35713. */
  35714. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35715. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35716. multiMaterial.id = parsedMultiMaterial.id;
  35717. if (BABYLON.Tags) {
  35718. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35719. }
  35720. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35721. var subMatId = parsedMultiMaterial.materials[matIndex];
  35722. if (subMatId) {
  35723. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35724. }
  35725. else {
  35726. multiMaterial.subMaterials.push(null);
  35727. }
  35728. }
  35729. return multiMaterial;
  35730. };
  35731. /**
  35732. * Creates a material from parsed material data
  35733. * @param parsedMaterial defines parsed material data
  35734. * @param scene defines the hosting scene
  35735. * @param rootUrl defines the root URL to use to load textures
  35736. * @returns a new material
  35737. */
  35738. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35739. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35740. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35741. }
  35742. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35743. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35744. if (!BABYLON.LegacyPBRMaterial) {
  35745. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35746. return;
  35747. }
  35748. }
  35749. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35750. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35751. };
  35752. // Triangle views
  35753. Material._TriangleFillMode = 0;
  35754. Material._WireFrameFillMode = 1;
  35755. Material._PointFillMode = 2;
  35756. // Draw modes
  35757. Material._PointListDrawMode = 3;
  35758. Material._LineListDrawMode = 4;
  35759. Material._LineLoopDrawMode = 5;
  35760. Material._LineStripDrawMode = 6;
  35761. Material._TriangleStripDrawMode = 7;
  35762. Material._TriangleFanDrawMode = 8;
  35763. /**
  35764. * Stores the clock-wise side orientation
  35765. */
  35766. Material._ClockWiseSideOrientation = 0;
  35767. /**
  35768. * Stores the counter clock-wise side orientation
  35769. */
  35770. Material._CounterClockWiseSideOrientation = 1;
  35771. /**
  35772. * The dirty texture flag value
  35773. */
  35774. Material._TextureDirtyFlag = 1;
  35775. /**
  35776. * The dirty light flag value
  35777. */
  35778. Material._LightDirtyFlag = 2;
  35779. /**
  35780. * The dirty fresnel flag value
  35781. */
  35782. Material._FresnelDirtyFlag = 4;
  35783. /**
  35784. * The dirty attribute flag value
  35785. */
  35786. Material._AttributesDirtyFlag = 8;
  35787. /**
  35788. * The dirty misc flag value
  35789. */
  35790. Material._MiscDirtyFlag = 16;
  35791. __decorate([
  35792. BABYLON.serialize()
  35793. ], Material.prototype, "id", void 0);
  35794. __decorate([
  35795. BABYLON.serialize()
  35796. ], Material.prototype, "uniqueId", void 0);
  35797. __decorate([
  35798. BABYLON.serialize()
  35799. ], Material.prototype, "name", void 0);
  35800. __decorate([
  35801. BABYLON.serialize()
  35802. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35803. __decorate([
  35804. BABYLON.serialize()
  35805. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35806. __decorate([
  35807. BABYLON.serialize()
  35808. ], Material.prototype, "state", void 0);
  35809. __decorate([
  35810. BABYLON.serialize("alpha")
  35811. ], Material.prototype, "_alpha", void 0);
  35812. __decorate([
  35813. BABYLON.serialize("backFaceCulling")
  35814. ], Material.prototype, "_backFaceCulling", void 0);
  35815. __decorate([
  35816. BABYLON.serialize()
  35817. ], Material.prototype, "sideOrientation", void 0);
  35818. __decorate([
  35819. BABYLON.serialize("alphaMode")
  35820. ], Material.prototype, "_alphaMode", void 0);
  35821. __decorate([
  35822. BABYLON.serialize()
  35823. ], Material.prototype, "_needDepthPrePass", void 0);
  35824. __decorate([
  35825. BABYLON.serialize()
  35826. ], Material.prototype, "disableDepthWrite", void 0);
  35827. __decorate([
  35828. BABYLON.serialize()
  35829. ], Material.prototype, "forceDepthWrite", void 0);
  35830. __decorate([
  35831. BABYLON.serialize()
  35832. ], Material.prototype, "separateCullingPass", void 0);
  35833. __decorate([
  35834. BABYLON.serialize("fogEnabled")
  35835. ], Material.prototype, "_fogEnabled", void 0);
  35836. __decorate([
  35837. BABYLON.serialize()
  35838. ], Material.prototype, "pointSize", void 0);
  35839. __decorate([
  35840. BABYLON.serialize()
  35841. ], Material.prototype, "zOffset", void 0);
  35842. __decorate([
  35843. BABYLON.serialize()
  35844. ], Material.prototype, "wireframe", null);
  35845. __decorate([
  35846. BABYLON.serialize()
  35847. ], Material.prototype, "pointsCloud", null);
  35848. __decorate([
  35849. BABYLON.serialize()
  35850. ], Material.prototype, "fillMode", null);
  35851. return Material;
  35852. }());
  35853. BABYLON.Material = Material;
  35854. })(BABYLON || (BABYLON = {}));
  35855. //# sourceMappingURL=babylon.material.js.map
  35856. var BABYLON;
  35857. (function (BABYLON) {
  35858. var UniformBuffer = /** @class */ (function () {
  35859. /**
  35860. * Uniform buffer objects.
  35861. *
  35862. * Handles blocks of uniform on the GPU.
  35863. *
  35864. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35865. *
  35866. * For more information, please refer to :
  35867. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35868. */
  35869. function UniformBuffer(engine, data, dynamic) {
  35870. this._engine = engine;
  35871. this._noUBO = !engine.supportsUniformBuffers;
  35872. this._dynamic = dynamic;
  35873. this._data = data || [];
  35874. this._uniformLocations = {};
  35875. this._uniformSizes = {};
  35876. this._uniformLocationPointer = 0;
  35877. this._needSync = false;
  35878. if (this._noUBO) {
  35879. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35880. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35881. this.updateFloat = this._updateFloatForEffect;
  35882. this.updateFloat2 = this._updateFloat2ForEffect;
  35883. this.updateFloat3 = this._updateFloat3ForEffect;
  35884. this.updateFloat4 = this._updateFloat4ForEffect;
  35885. this.updateMatrix = this._updateMatrixForEffect;
  35886. this.updateVector3 = this._updateVector3ForEffect;
  35887. this.updateVector4 = this._updateVector4ForEffect;
  35888. this.updateColor3 = this._updateColor3ForEffect;
  35889. this.updateColor4 = this._updateColor4ForEffect;
  35890. }
  35891. else {
  35892. this._engine._uniformBuffers.push(this);
  35893. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35894. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35895. this.updateFloat = this._updateFloatForUniform;
  35896. this.updateFloat2 = this._updateFloat2ForUniform;
  35897. this.updateFloat3 = this._updateFloat3ForUniform;
  35898. this.updateFloat4 = this._updateFloat4ForUniform;
  35899. this.updateMatrix = this._updateMatrixForUniform;
  35900. this.updateVector3 = this._updateVector3ForUniform;
  35901. this.updateVector4 = this._updateVector4ForUniform;
  35902. this.updateColor3 = this._updateColor3ForUniform;
  35903. this.updateColor4 = this._updateColor4ForUniform;
  35904. }
  35905. }
  35906. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35907. // Properties
  35908. /**
  35909. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35910. * or just falling back on setUniformXXX calls.
  35911. */
  35912. get: function () {
  35913. return !this._noUBO;
  35914. },
  35915. enumerable: true,
  35916. configurable: true
  35917. });
  35918. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35919. /**
  35920. * Indicates if the WebGL underlying uniform buffer is in sync
  35921. * with the javascript cache data.
  35922. */
  35923. get: function () {
  35924. return !this._needSync;
  35925. },
  35926. enumerable: true,
  35927. configurable: true
  35928. });
  35929. /**
  35930. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35931. * Also, a dynamic UniformBuffer will disable cache verification and always
  35932. * update the underlying WebGL uniform buffer to the GPU.
  35933. */
  35934. UniformBuffer.prototype.isDynamic = function () {
  35935. return this._dynamic !== undefined;
  35936. };
  35937. /**
  35938. * The data cache on JS side.
  35939. */
  35940. UniformBuffer.prototype.getData = function () {
  35941. return this._bufferData;
  35942. };
  35943. /**
  35944. * The underlying WebGL Uniform buffer.
  35945. */
  35946. UniformBuffer.prototype.getBuffer = function () {
  35947. return this._buffer;
  35948. };
  35949. /**
  35950. * std140 layout specifies how to align data within an UBO structure.
  35951. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35952. * for specs.
  35953. */
  35954. UniformBuffer.prototype._fillAlignment = function (size) {
  35955. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35956. // and 4x4 matrices
  35957. // TODO : change if other types are used
  35958. var alignment;
  35959. if (size <= 2) {
  35960. alignment = size;
  35961. }
  35962. else {
  35963. alignment = 4;
  35964. }
  35965. if ((this._uniformLocationPointer % alignment) !== 0) {
  35966. var oldPointer = this._uniformLocationPointer;
  35967. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35968. var diff = this._uniformLocationPointer - oldPointer;
  35969. for (var i = 0; i < diff; i++) {
  35970. this._data.push(0);
  35971. }
  35972. }
  35973. };
  35974. /**
  35975. * Adds an uniform in the buffer.
  35976. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35977. * for the layout to be correct !
  35978. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35979. * @param {number|number[]} size Data size, or data directly.
  35980. */
  35981. UniformBuffer.prototype.addUniform = function (name, size) {
  35982. if (this._noUBO) {
  35983. return;
  35984. }
  35985. if (this._uniformLocations[name] !== undefined) {
  35986. // Already existing uniform
  35987. return;
  35988. }
  35989. // This function must be called in the order of the shader layout !
  35990. // size can be the size of the uniform, or data directly
  35991. var data;
  35992. if (size instanceof Array) {
  35993. data = size;
  35994. size = data.length;
  35995. }
  35996. else {
  35997. size = size;
  35998. data = [];
  35999. // Fill with zeros
  36000. for (var i = 0; i < size; i++) {
  36001. data.push(0);
  36002. }
  36003. }
  36004. this._fillAlignment(size);
  36005. this._uniformSizes[name] = size;
  36006. this._uniformLocations[name] = this._uniformLocationPointer;
  36007. this._uniformLocationPointer += size;
  36008. for (var i = 0; i < size; i++) {
  36009. this._data.push(data[i]);
  36010. }
  36011. this._needSync = true;
  36012. };
  36013. /**
  36014. * Wrapper for addUniform.
  36015. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36016. * @param {Matrix} mat A 4x4 matrix.
  36017. */
  36018. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36019. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36020. };
  36021. /**
  36022. * Wrapper for addUniform.
  36023. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36024. * @param {number} x
  36025. * @param {number} y
  36026. */
  36027. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36028. var temp = [x, y];
  36029. this.addUniform(name, temp);
  36030. };
  36031. /**
  36032. * Wrapper for addUniform.
  36033. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36034. * @param {number} x
  36035. * @param {number} y
  36036. * @param {number} z
  36037. */
  36038. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36039. var temp = [x, y, z];
  36040. this.addUniform(name, temp);
  36041. };
  36042. /**
  36043. * Wrapper for addUniform.
  36044. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36045. * @param {Color3} color
  36046. */
  36047. UniformBuffer.prototype.addColor3 = function (name, color) {
  36048. var temp = new Array();
  36049. color.toArray(temp);
  36050. this.addUniform(name, temp);
  36051. };
  36052. /**
  36053. * Wrapper for addUniform.
  36054. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36055. * @param {Color3} color
  36056. * @param {number} alpha
  36057. */
  36058. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36059. var temp = new Array();
  36060. color.toArray(temp);
  36061. temp.push(alpha);
  36062. this.addUniform(name, temp);
  36063. };
  36064. /**
  36065. * Wrapper for addUniform.
  36066. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36067. * @param {Vector3} vector
  36068. */
  36069. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36070. var temp = new Array();
  36071. vector.toArray(temp);
  36072. this.addUniform(name, temp);
  36073. };
  36074. /**
  36075. * Wrapper for addUniform.
  36076. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36077. */
  36078. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36079. this.addUniform(name, 12);
  36080. };
  36081. /**
  36082. * Wrapper for addUniform.
  36083. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36084. */
  36085. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36086. this.addUniform(name, 8);
  36087. };
  36088. /**
  36089. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36090. */
  36091. UniformBuffer.prototype.create = function () {
  36092. if (this._noUBO) {
  36093. return;
  36094. }
  36095. if (this._buffer) {
  36096. return; // nothing to do
  36097. }
  36098. // See spec, alignment must be filled as a vec4
  36099. this._fillAlignment(4);
  36100. this._bufferData = new Float32Array(this._data);
  36101. this._rebuild();
  36102. this._needSync = true;
  36103. };
  36104. UniformBuffer.prototype._rebuild = function () {
  36105. if (this._noUBO) {
  36106. return;
  36107. }
  36108. if (this._dynamic) {
  36109. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36110. }
  36111. else {
  36112. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36113. }
  36114. };
  36115. /**
  36116. * Updates the WebGL Uniform Buffer on the GPU.
  36117. * If the `dynamic` flag is set to true, no cache comparison is done.
  36118. * Otherwise, the buffer will be updated only if the cache differs.
  36119. */
  36120. UniformBuffer.prototype.update = function () {
  36121. if (!this._buffer) {
  36122. this.create();
  36123. return;
  36124. }
  36125. if (!this._dynamic && !this._needSync) {
  36126. return;
  36127. }
  36128. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36129. this._needSync = false;
  36130. };
  36131. /**
  36132. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36133. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36134. * @param {number[]|Float32Array} data Flattened data
  36135. * @param {number} size Size of the data.
  36136. */
  36137. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36138. var location = this._uniformLocations[uniformName];
  36139. if (location === undefined) {
  36140. if (this._buffer) {
  36141. // Cannot add an uniform if the buffer is already created
  36142. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36143. return;
  36144. }
  36145. this.addUniform(uniformName, size);
  36146. location = this._uniformLocations[uniformName];
  36147. }
  36148. if (!this._buffer) {
  36149. this.create();
  36150. }
  36151. if (!this._dynamic) {
  36152. // Cache for static uniform buffers
  36153. var changed = false;
  36154. for (var i = 0; i < size; i++) {
  36155. if (this._bufferData[location + i] !== data[i]) {
  36156. changed = true;
  36157. this._bufferData[location + i] = data[i];
  36158. }
  36159. }
  36160. this._needSync = this._needSync || changed;
  36161. }
  36162. else {
  36163. // No cache for dynamic
  36164. for (var i = 0; i < size; i++) {
  36165. this._bufferData[location + i] = data[i];
  36166. }
  36167. }
  36168. };
  36169. // Update methods
  36170. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36171. // To match std140, matrix must be realigned
  36172. for (var i = 0; i < 3; i++) {
  36173. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36174. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36175. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36176. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36177. }
  36178. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36179. };
  36180. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36181. this._currentEffect.setMatrix3x3(name, matrix);
  36182. };
  36183. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36184. this._currentEffect.setMatrix2x2(name, matrix);
  36185. };
  36186. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36187. // To match std140, matrix must be realigned
  36188. for (var i = 0; i < 2; i++) {
  36189. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36190. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36191. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36192. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36193. }
  36194. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36195. };
  36196. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36197. this._currentEffect.setFloat(name, x);
  36198. };
  36199. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36200. UniformBuffer._tempBuffer[0] = x;
  36201. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36202. };
  36203. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36204. if (suffix === void 0) { suffix = ""; }
  36205. this._currentEffect.setFloat2(name + suffix, x, y);
  36206. };
  36207. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36208. if (suffix === void 0) { suffix = ""; }
  36209. UniformBuffer._tempBuffer[0] = x;
  36210. UniformBuffer._tempBuffer[1] = y;
  36211. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36212. };
  36213. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36214. if (suffix === void 0) { suffix = ""; }
  36215. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36216. };
  36217. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36218. if (suffix === void 0) { suffix = ""; }
  36219. UniformBuffer._tempBuffer[0] = x;
  36220. UniformBuffer._tempBuffer[1] = y;
  36221. UniformBuffer._tempBuffer[2] = z;
  36222. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36223. };
  36224. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36225. if (suffix === void 0) { suffix = ""; }
  36226. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36227. };
  36228. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36229. if (suffix === void 0) { suffix = ""; }
  36230. UniformBuffer._tempBuffer[0] = x;
  36231. UniformBuffer._tempBuffer[1] = y;
  36232. UniformBuffer._tempBuffer[2] = z;
  36233. UniformBuffer._tempBuffer[3] = w;
  36234. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36235. };
  36236. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36237. this._currentEffect.setMatrix(name, mat);
  36238. };
  36239. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36240. this.updateUniform(name, mat.toArray(), 16);
  36241. };
  36242. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36243. this._currentEffect.setVector3(name, vector);
  36244. };
  36245. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36246. vector.toArray(UniformBuffer._tempBuffer);
  36247. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36248. };
  36249. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36250. this._currentEffect.setVector4(name, vector);
  36251. };
  36252. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36253. vector.toArray(UniformBuffer._tempBuffer);
  36254. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36255. };
  36256. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36257. if (suffix === void 0) { suffix = ""; }
  36258. this._currentEffect.setColor3(name + suffix, color);
  36259. };
  36260. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36261. if (suffix === void 0) { suffix = ""; }
  36262. color.toArray(UniformBuffer._tempBuffer);
  36263. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36264. };
  36265. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36266. if (suffix === void 0) { suffix = ""; }
  36267. this._currentEffect.setColor4(name + suffix, color, alpha);
  36268. };
  36269. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36270. if (suffix === void 0) { suffix = ""; }
  36271. color.toArray(UniformBuffer._tempBuffer);
  36272. UniformBuffer._tempBuffer[3] = alpha;
  36273. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36274. };
  36275. /**
  36276. * Sets a sampler uniform on the effect.
  36277. * @param {string} name Name of the sampler.
  36278. * @param {Texture} texture
  36279. */
  36280. UniformBuffer.prototype.setTexture = function (name, texture) {
  36281. this._currentEffect.setTexture(name, texture);
  36282. };
  36283. /**
  36284. * Directly updates the value of the uniform in the cache AND on the GPU.
  36285. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36286. * @param {number[]|Float32Array} data Flattened data
  36287. */
  36288. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36289. this.updateUniform(uniformName, data, data.length);
  36290. this.update();
  36291. };
  36292. /**
  36293. * Binds this uniform buffer to an effect.
  36294. * @param {Effect} effect
  36295. * @param {string} name Name of the uniform block in the shader.
  36296. */
  36297. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36298. this._currentEffect = effect;
  36299. if (this._noUBO || !this._buffer) {
  36300. return;
  36301. }
  36302. effect.bindUniformBuffer(this._buffer, name);
  36303. };
  36304. /**
  36305. * Disposes the uniform buffer.
  36306. */
  36307. UniformBuffer.prototype.dispose = function () {
  36308. if (this._noUBO) {
  36309. return;
  36310. }
  36311. var index = this._engine._uniformBuffers.indexOf(this);
  36312. if (index !== -1) {
  36313. this._engine._uniformBuffers.splice(index, 1);
  36314. }
  36315. if (!this._buffer) {
  36316. return;
  36317. }
  36318. if (this._engine._releaseBuffer(this._buffer)) {
  36319. this._buffer = null;
  36320. }
  36321. };
  36322. // Pool for avoiding memory leaks
  36323. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36324. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36325. return UniformBuffer;
  36326. }());
  36327. BABYLON.UniformBuffer = UniformBuffer;
  36328. })(BABYLON || (BABYLON = {}));
  36329. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36330. var BABYLON;
  36331. (function (BABYLON) {
  36332. /**
  36333. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36334. */
  36335. var VertexData = /** @class */ (function () {
  36336. function VertexData() {
  36337. }
  36338. /**
  36339. * Uses the passed data array to set the set the values for the specified kind of data
  36340. * @param data a linear array of floating numbers
  36341. * @param kind the type of data that is being set, eg positions, colors etc
  36342. */
  36343. VertexData.prototype.set = function (data, kind) {
  36344. switch (kind) {
  36345. case BABYLON.VertexBuffer.PositionKind:
  36346. this.positions = data;
  36347. break;
  36348. case BABYLON.VertexBuffer.NormalKind:
  36349. this.normals = data;
  36350. break;
  36351. case BABYLON.VertexBuffer.TangentKind:
  36352. this.tangents = data;
  36353. break;
  36354. case BABYLON.VertexBuffer.UVKind:
  36355. this.uvs = data;
  36356. break;
  36357. case BABYLON.VertexBuffer.UV2Kind:
  36358. this.uvs2 = data;
  36359. break;
  36360. case BABYLON.VertexBuffer.UV3Kind:
  36361. this.uvs3 = data;
  36362. break;
  36363. case BABYLON.VertexBuffer.UV4Kind:
  36364. this.uvs4 = data;
  36365. break;
  36366. case BABYLON.VertexBuffer.UV5Kind:
  36367. this.uvs5 = data;
  36368. break;
  36369. case BABYLON.VertexBuffer.UV6Kind:
  36370. this.uvs6 = data;
  36371. break;
  36372. case BABYLON.VertexBuffer.ColorKind:
  36373. this.colors = data;
  36374. break;
  36375. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36376. this.matricesIndices = data;
  36377. break;
  36378. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36379. this.matricesWeights = data;
  36380. break;
  36381. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36382. this.matricesIndicesExtra = data;
  36383. break;
  36384. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36385. this.matricesWeightsExtra = data;
  36386. break;
  36387. }
  36388. };
  36389. /**
  36390. * Associates the vertexData to the passed Mesh.
  36391. * Sets it as updatable or not (default `false`)
  36392. * @param mesh the mesh the vertexData is applied to
  36393. * @param updatable when used and having the value true allows new data to update the vertexData
  36394. * @returns the VertexData
  36395. */
  36396. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36397. this._applyTo(mesh, updatable);
  36398. return this;
  36399. };
  36400. /**
  36401. * Associates the vertexData to the passed Geometry.
  36402. * Sets it as updatable or not (default `false`)
  36403. * @param geometry the geometry the vertexData is applied to
  36404. * @param updatable when used and having the value true allows new data to update the vertexData
  36405. * @returns VertexData
  36406. */
  36407. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36408. this._applyTo(geometry, updatable);
  36409. return this;
  36410. };
  36411. /**
  36412. * Updates the associated mesh
  36413. * @param mesh the mesh to be updated
  36414. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36415. * @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
  36416. * @returns VertexData
  36417. */
  36418. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36419. this._update(mesh);
  36420. return this;
  36421. };
  36422. /**
  36423. * Updates the associated geometry
  36424. * @param geometry the geometry to be updated
  36425. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36426. * @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
  36427. * @returns VertexData.
  36428. */
  36429. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36430. this._update(geometry);
  36431. return this;
  36432. };
  36433. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36434. if (updatable === void 0) { updatable = false; }
  36435. if (this.positions) {
  36436. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36437. }
  36438. if (this.normals) {
  36439. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36440. }
  36441. if (this.tangents) {
  36442. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36443. }
  36444. if (this.uvs) {
  36445. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36446. }
  36447. if (this.uvs2) {
  36448. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36449. }
  36450. if (this.uvs3) {
  36451. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36452. }
  36453. if (this.uvs4) {
  36454. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36455. }
  36456. if (this.uvs5) {
  36457. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36458. }
  36459. if (this.uvs6) {
  36460. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36461. }
  36462. if (this.colors) {
  36463. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36464. }
  36465. if (this.matricesIndices) {
  36466. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36467. }
  36468. if (this.matricesWeights) {
  36469. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36470. }
  36471. if (this.matricesIndicesExtra) {
  36472. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36473. }
  36474. if (this.matricesWeightsExtra) {
  36475. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36476. }
  36477. if (this.indices) {
  36478. meshOrGeometry.setIndices(this.indices, null, updatable);
  36479. }
  36480. else {
  36481. meshOrGeometry.setIndices([], null);
  36482. }
  36483. return this;
  36484. };
  36485. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36486. if (this.positions) {
  36487. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36488. }
  36489. if (this.normals) {
  36490. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36491. }
  36492. if (this.tangents) {
  36493. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36494. }
  36495. if (this.uvs) {
  36496. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36497. }
  36498. if (this.uvs2) {
  36499. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36500. }
  36501. if (this.uvs3) {
  36502. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36503. }
  36504. if (this.uvs4) {
  36505. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36506. }
  36507. if (this.uvs5) {
  36508. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36509. }
  36510. if (this.uvs6) {
  36511. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36512. }
  36513. if (this.colors) {
  36514. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36515. }
  36516. if (this.matricesIndices) {
  36517. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36518. }
  36519. if (this.matricesWeights) {
  36520. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36521. }
  36522. if (this.matricesIndicesExtra) {
  36523. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36524. }
  36525. if (this.matricesWeightsExtra) {
  36526. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36527. }
  36528. if (this.indices) {
  36529. meshOrGeometry.setIndices(this.indices, null);
  36530. }
  36531. return this;
  36532. };
  36533. /**
  36534. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36535. * @param matrix the transforming matrix
  36536. * @returns the VertexData
  36537. */
  36538. VertexData.prototype.transform = function (matrix) {
  36539. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36540. var transformed = BABYLON.Vector3.Zero();
  36541. var index;
  36542. if (this.positions) {
  36543. var position = BABYLON.Vector3.Zero();
  36544. for (index = 0; index < this.positions.length; index += 3) {
  36545. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36546. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36547. this.positions[index] = transformed.x;
  36548. this.positions[index + 1] = transformed.y;
  36549. this.positions[index + 2] = transformed.z;
  36550. }
  36551. }
  36552. if (this.normals) {
  36553. var normal = BABYLON.Vector3.Zero();
  36554. for (index = 0; index < this.normals.length; index += 3) {
  36555. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36556. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36557. this.normals[index] = transformed.x;
  36558. this.normals[index + 1] = transformed.y;
  36559. this.normals[index + 2] = transformed.z;
  36560. }
  36561. }
  36562. if (this.tangents) {
  36563. var tangent = BABYLON.Vector4.Zero();
  36564. var tangentTransformed = BABYLON.Vector4.Zero();
  36565. for (index = 0; index < this.tangents.length; index += 4) {
  36566. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36567. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36568. this.tangents[index] = tangentTransformed.x;
  36569. this.tangents[index + 1] = tangentTransformed.y;
  36570. this.tangents[index + 2] = tangentTransformed.z;
  36571. this.tangents[index + 3] = tangentTransformed.w;
  36572. }
  36573. }
  36574. if (flip && this.indices) {
  36575. for (index = 0; index < this.indices.length; index += 3) {
  36576. var tmp = this.indices[index + 1];
  36577. this.indices[index + 1] = this.indices[index + 2];
  36578. this.indices[index + 2] = tmp;
  36579. }
  36580. }
  36581. return this;
  36582. };
  36583. /**
  36584. * Merges the passed VertexData into the current one
  36585. * @param other the VertexData to be merged into the current one
  36586. * @returns the modified VertexData
  36587. */
  36588. VertexData.prototype.merge = function (other) {
  36589. this._validate();
  36590. other._validate();
  36591. if (!this.normals !== !other.normals ||
  36592. !this.tangents !== !other.tangents ||
  36593. !this.uvs !== !other.uvs ||
  36594. !this.uvs2 !== !other.uvs2 ||
  36595. !this.uvs3 !== !other.uvs3 ||
  36596. !this.uvs4 !== !other.uvs4 ||
  36597. !this.uvs5 !== !other.uvs5 ||
  36598. !this.uvs6 !== !other.uvs6 ||
  36599. !this.colors !== !other.colors ||
  36600. !this.matricesIndices !== !other.matricesIndices ||
  36601. !this.matricesWeights !== !other.matricesWeights ||
  36602. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36603. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36604. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36605. }
  36606. if (other.indices) {
  36607. if (!this.indices) {
  36608. this.indices = [];
  36609. }
  36610. var offset = this.positions ? this.positions.length / 3 : 0;
  36611. for (var index = 0; index < other.indices.length; index++) {
  36612. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36613. this.indices.push(other.indices[index] + offset);
  36614. }
  36615. }
  36616. this.positions = this._mergeElement(this.positions, other.positions);
  36617. this.normals = this._mergeElement(this.normals, other.normals);
  36618. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36619. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36620. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36621. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36622. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36623. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36624. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36625. this.colors = this._mergeElement(this.colors, other.colors);
  36626. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36627. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36628. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36629. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36630. return this;
  36631. };
  36632. VertexData.prototype._mergeElement = function (source, other) {
  36633. if (!source) {
  36634. return other;
  36635. }
  36636. if (!other) {
  36637. return source;
  36638. }
  36639. var len = other.length + source.length;
  36640. var isSrcTypedArray = source instanceof Float32Array;
  36641. var isOthTypedArray = other instanceof Float32Array;
  36642. // use non-loop method when the source is Float32Array
  36643. if (isSrcTypedArray) {
  36644. var ret32 = new Float32Array(len);
  36645. ret32.set(source);
  36646. ret32.set(other, source.length);
  36647. return ret32;
  36648. // source is number[], when other is also use concat
  36649. }
  36650. else if (!isOthTypedArray) {
  36651. return source.concat(other);
  36652. // source is a number[], but other is a Float32Array, loop required
  36653. }
  36654. else {
  36655. var ret = source.slice(0); // copy source to a separate array
  36656. for (var i = 0, len = other.length; i < len; i++) {
  36657. ret.push(other[i]);
  36658. }
  36659. return ret;
  36660. }
  36661. };
  36662. VertexData.prototype._validate = function () {
  36663. if (!this.positions) {
  36664. throw new Error("Positions are required");
  36665. }
  36666. var getElementCount = function (kind, values) {
  36667. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36668. if ((values.length % stride) !== 0) {
  36669. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36670. }
  36671. return values.length / stride;
  36672. };
  36673. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36674. var validateElementCount = function (kind, values) {
  36675. var elementCount = getElementCount(kind, values);
  36676. if (elementCount !== positionsElementCount) {
  36677. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36678. }
  36679. };
  36680. if (this.normals)
  36681. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36682. if (this.tangents)
  36683. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36684. if (this.uvs)
  36685. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36686. if (this.uvs2)
  36687. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36688. if (this.uvs3)
  36689. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36690. if (this.uvs4)
  36691. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36692. if (this.uvs5)
  36693. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36694. if (this.uvs6)
  36695. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36696. if (this.colors)
  36697. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36698. if (this.matricesIndices)
  36699. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36700. if (this.matricesWeights)
  36701. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36702. if (this.matricesIndicesExtra)
  36703. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36704. if (this.matricesWeightsExtra)
  36705. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36706. };
  36707. /**
  36708. * Serializes the VertexData
  36709. * @returns a serialized object
  36710. */
  36711. VertexData.prototype.serialize = function () {
  36712. var serializationObject = this.serialize();
  36713. if (this.positions) {
  36714. serializationObject.positions = this.positions;
  36715. }
  36716. if (this.normals) {
  36717. serializationObject.normals = this.normals;
  36718. }
  36719. if (this.tangents) {
  36720. serializationObject.tangents = this.tangents;
  36721. }
  36722. if (this.uvs) {
  36723. serializationObject.uvs = this.uvs;
  36724. }
  36725. if (this.uvs2) {
  36726. serializationObject.uvs2 = this.uvs2;
  36727. }
  36728. if (this.uvs3) {
  36729. serializationObject.uvs3 = this.uvs3;
  36730. }
  36731. if (this.uvs4) {
  36732. serializationObject.uvs4 = this.uvs4;
  36733. }
  36734. if (this.uvs5) {
  36735. serializationObject.uvs5 = this.uvs5;
  36736. }
  36737. if (this.uvs6) {
  36738. serializationObject.uvs6 = this.uvs6;
  36739. }
  36740. if (this.colors) {
  36741. serializationObject.colors = this.colors;
  36742. }
  36743. if (this.matricesIndices) {
  36744. serializationObject.matricesIndices = this.matricesIndices;
  36745. serializationObject.matricesIndices._isExpanded = true;
  36746. }
  36747. if (this.matricesWeights) {
  36748. serializationObject.matricesWeights = this.matricesWeights;
  36749. }
  36750. if (this.matricesIndicesExtra) {
  36751. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36752. serializationObject.matricesIndicesExtra._isExpanded = true;
  36753. }
  36754. if (this.matricesWeightsExtra) {
  36755. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36756. }
  36757. serializationObject.indices = this.indices;
  36758. return serializationObject;
  36759. };
  36760. // Statics
  36761. /**
  36762. * Extracts the vertexData from a mesh
  36763. * @param mesh the mesh from which to extract the VertexData
  36764. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36765. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36766. * @returns the object VertexData associated to the passed mesh
  36767. */
  36768. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36769. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36770. };
  36771. /**
  36772. * Extracts the vertexData from the geometry
  36773. * @param geometry the geometry from which to extract the VertexData
  36774. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36775. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36776. * @returns the object VertexData associated to the passed mesh
  36777. */
  36778. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36779. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36780. };
  36781. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36782. var result = new VertexData();
  36783. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36784. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36785. }
  36786. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36787. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36788. }
  36789. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36790. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36791. }
  36792. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36793. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36794. }
  36795. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36796. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36797. }
  36798. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36799. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36800. }
  36801. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36802. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36803. }
  36804. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36805. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36806. }
  36807. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36808. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36809. }
  36810. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36811. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36812. }
  36813. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36814. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36815. }
  36816. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36817. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36818. }
  36819. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36820. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36821. }
  36822. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36823. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36824. }
  36825. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36826. return result;
  36827. };
  36828. /**
  36829. * Creates the VertexData for a Ribbon
  36830. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36831. * * pathArray array of paths, each of which an array of successive Vector3
  36832. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36833. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36834. * * 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
  36835. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36836. * * 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)
  36837. * * 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)
  36838. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36839. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36840. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36841. * @returns the VertexData of the ribbon
  36842. */
  36843. VertexData.CreateRibbon = function (options) {
  36844. var pathArray = options.pathArray;
  36845. var closeArray = options.closeArray || false;
  36846. var closePath = options.closePath || false;
  36847. var invertUV = options.invertUV || false;
  36848. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36849. var offset = options.offset || defaultOffset;
  36850. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36851. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36852. var customUV = options.uvs;
  36853. var customColors = options.colors;
  36854. var positions = [];
  36855. var indices = [];
  36856. var normals = [];
  36857. var uvs = [];
  36858. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36859. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36860. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36861. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36862. var minlg; // minimal length among all paths from pathArray
  36863. var lg = []; // array of path lengths : nb of vertex per path
  36864. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36865. var p; // path iterator
  36866. var i; // point iterator
  36867. var j; // point iterator
  36868. // if single path in pathArray
  36869. if (pathArray.length < 2) {
  36870. var ar1 = [];
  36871. var ar2 = [];
  36872. for (i = 0; i < pathArray[0].length - offset; i++) {
  36873. ar1.push(pathArray[0][i]);
  36874. ar2.push(pathArray[0][i + offset]);
  36875. }
  36876. pathArray = [ar1, ar2];
  36877. }
  36878. // positions and horizontal distances (u)
  36879. var idc = 0;
  36880. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36881. var path;
  36882. var l;
  36883. minlg = pathArray[0].length;
  36884. var vectlg;
  36885. var dist;
  36886. for (p = 0; p < pathArray.length; p++) {
  36887. uTotalDistance[p] = 0;
  36888. us[p] = [0];
  36889. path = pathArray[p];
  36890. l = path.length;
  36891. minlg = (minlg < l) ? minlg : l;
  36892. j = 0;
  36893. while (j < l) {
  36894. positions.push(path[j].x, path[j].y, path[j].z);
  36895. if (j > 0) {
  36896. vectlg = path[j].subtract(path[j - 1]).length();
  36897. dist = vectlg + uTotalDistance[p];
  36898. us[p].push(dist);
  36899. uTotalDistance[p] = dist;
  36900. }
  36901. j++;
  36902. }
  36903. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36904. j--;
  36905. positions.push(path[0].x, path[0].y, path[0].z);
  36906. vectlg = path[j].subtract(path[0]).length();
  36907. dist = vectlg + uTotalDistance[p];
  36908. us[p].push(dist);
  36909. uTotalDistance[p] = dist;
  36910. }
  36911. lg[p] = l + closePathCorr;
  36912. idx[p] = idc;
  36913. idc += (l + closePathCorr);
  36914. }
  36915. // vertical distances (v)
  36916. var path1;
  36917. var path2;
  36918. var vertex1 = null;
  36919. var vertex2 = null;
  36920. for (i = 0; i < minlg + closePathCorr; i++) {
  36921. vTotalDistance[i] = 0;
  36922. vs[i] = [0];
  36923. for (p = 0; p < pathArray.length - 1; p++) {
  36924. path1 = pathArray[p];
  36925. path2 = pathArray[p + 1];
  36926. if (i === minlg) { // closePath
  36927. vertex1 = path1[0];
  36928. vertex2 = path2[0];
  36929. }
  36930. else {
  36931. vertex1 = path1[i];
  36932. vertex2 = path2[i];
  36933. }
  36934. vectlg = vertex2.subtract(vertex1).length();
  36935. dist = vectlg + vTotalDistance[i];
  36936. vs[i].push(dist);
  36937. vTotalDistance[i] = dist;
  36938. }
  36939. if (closeArray && vertex2 && vertex1) {
  36940. path1 = pathArray[p];
  36941. path2 = pathArray[0];
  36942. if (i === minlg) { // closePath
  36943. vertex2 = path2[0];
  36944. }
  36945. vectlg = vertex2.subtract(vertex1).length();
  36946. dist = vectlg + vTotalDistance[i];
  36947. vTotalDistance[i] = dist;
  36948. }
  36949. }
  36950. // uvs
  36951. var u;
  36952. var v;
  36953. if (customUV) {
  36954. for (p = 0; p < customUV.length; p++) {
  36955. uvs.push(customUV[p].x, customUV[p].y);
  36956. }
  36957. }
  36958. else {
  36959. for (p = 0; p < pathArray.length; p++) {
  36960. for (i = 0; i < minlg + closePathCorr; i++) {
  36961. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36962. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36963. if (invertUV) {
  36964. uvs.push(v, u);
  36965. }
  36966. else {
  36967. uvs.push(u, v);
  36968. }
  36969. }
  36970. }
  36971. }
  36972. // indices
  36973. p = 0; // path index
  36974. var pi = 0; // positions array index
  36975. var l1 = lg[p] - 1; // path1 length
  36976. var l2 = lg[p + 1] - 1; // path2 length
  36977. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36978. var shft = idx[1] - idx[0]; // shift
  36979. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36980. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36981. // 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
  36982. indices.push(pi, pi + shft, pi + 1);
  36983. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36984. pi += 1;
  36985. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36986. p++;
  36987. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36988. shft = idx[0] - idx[p];
  36989. l1 = lg[p] - 1;
  36990. l2 = lg[0] - 1;
  36991. }
  36992. else {
  36993. shft = idx[p + 1] - idx[p];
  36994. l1 = lg[p] - 1;
  36995. l2 = lg[p + 1] - 1;
  36996. }
  36997. pi = idx[p];
  36998. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36999. }
  37000. }
  37001. // normals
  37002. VertexData.ComputeNormals(positions, indices, normals);
  37003. if (closePath) { // update both the first and last vertex normals to their average value
  37004. var indexFirst = 0;
  37005. var indexLast = 0;
  37006. for (p = 0; p < pathArray.length; p++) {
  37007. indexFirst = idx[p] * 3;
  37008. if (p + 1 < pathArray.length) {
  37009. indexLast = (idx[p + 1] - 1) * 3;
  37010. }
  37011. else {
  37012. indexLast = normals.length - 3;
  37013. }
  37014. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37015. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37016. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37017. normals[indexLast] = normals[indexFirst];
  37018. normals[indexLast + 1] = normals[indexFirst + 1];
  37019. normals[indexLast + 2] = normals[indexFirst + 2];
  37020. }
  37021. }
  37022. // sides
  37023. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37024. // Colors
  37025. var colors = null;
  37026. if (customColors) {
  37027. colors = new Float32Array(customColors.length * 4);
  37028. for (var c = 0; c < customColors.length; c++) {
  37029. colors[c * 4] = customColors[c].r;
  37030. colors[c * 4 + 1] = customColors[c].g;
  37031. colors[c * 4 + 2] = customColors[c].b;
  37032. colors[c * 4 + 3] = customColors[c].a;
  37033. }
  37034. }
  37035. // Result
  37036. var vertexData = new VertexData();
  37037. var positions32 = new Float32Array(positions);
  37038. var normals32 = new Float32Array(normals);
  37039. var uvs32 = new Float32Array(uvs);
  37040. vertexData.indices = indices;
  37041. vertexData.positions = positions32;
  37042. vertexData.normals = normals32;
  37043. vertexData.uvs = uvs32;
  37044. if (colors) {
  37045. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37046. }
  37047. if (closePath) {
  37048. vertexData._idx = idx;
  37049. }
  37050. return vertexData;
  37051. };
  37052. /**
  37053. * Creates the VertexData for a box
  37054. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37055. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37056. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37057. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37058. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37059. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37060. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37061. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37062. * * 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)
  37063. * * 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)
  37064. * @returns the VertexData of the box
  37065. */
  37066. VertexData.CreateBox = function (options) {
  37067. var normalsSource = [
  37068. new BABYLON.Vector3(0, 0, 1),
  37069. new BABYLON.Vector3(0, 0, -1),
  37070. new BABYLON.Vector3(1, 0, 0),
  37071. new BABYLON.Vector3(-1, 0, 0),
  37072. new BABYLON.Vector3(0, 1, 0),
  37073. new BABYLON.Vector3(0, -1, 0)
  37074. ];
  37075. var indices = [];
  37076. var positions = [];
  37077. var normals = [];
  37078. var uvs = [];
  37079. var width = options.width || options.size || 1;
  37080. var height = options.height || options.size || 1;
  37081. var depth = options.depth || options.size || 1;
  37082. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37083. var faceUV = options.faceUV || new Array(6);
  37084. var faceColors = options.faceColors;
  37085. var colors = [];
  37086. // default face colors and UV if undefined
  37087. for (var f = 0; f < 6; f++) {
  37088. if (faceUV[f] === undefined) {
  37089. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37090. }
  37091. if (faceColors && faceColors[f] === undefined) {
  37092. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37093. }
  37094. }
  37095. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37096. // Create each face in turn.
  37097. for (var index = 0; index < normalsSource.length; index++) {
  37098. var normal = normalsSource[index];
  37099. // Get two vectors perpendicular to the face normal and to each other.
  37100. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37101. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37102. // Six indices (two triangles) per face.
  37103. var verticesLength = positions.length / 3;
  37104. indices.push(verticesLength);
  37105. indices.push(verticesLength + 1);
  37106. indices.push(verticesLength + 2);
  37107. indices.push(verticesLength);
  37108. indices.push(verticesLength + 2);
  37109. indices.push(verticesLength + 3);
  37110. // Four vertices per face.
  37111. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37112. positions.push(vertex.x, vertex.y, vertex.z);
  37113. normals.push(normal.x, normal.y, normal.z);
  37114. uvs.push(faceUV[index].z, faceUV[index].w);
  37115. if (faceColors) {
  37116. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37117. }
  37118. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37119. positions.push(vertex.x, vertex.y, vertex.z);
  37120. normals.push(normal.x, normal.y, normal.z);
  37121. uvs.push(faceUV[index].x, faceUV[index].w);
  37122. if (faceColors) {
  37123. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37124. }
  37125. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37126. positions.push(vertex.x, vertex.y, vertex.z);
  37127. normals.push(normal.x, normal.y, normal.z);
  37128. uvs.push(faceUV[index].x, faceUV[index].y);
  37129. if (faceColors) {
  37130. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37131. }
  37132. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37133. positions.push(vertex.x, vertex.y, vertex.z);
  37134. normals.push(normal.x, normal.y, normal.z);
  37135. uvs.push(faceUV[index].z, faceUV[index].y);
  37136. if (faceColors) {
  37137. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37138. }
  37139. }
  37140. // sides
  37141. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37142. // Result
  37143. var vertexData = new VertexData();
  37144. vertexData.indices = indices;
  37145. vertexData.positions = positions;
  37146. vertexData.normals = normals;
  37147. vertexData.uvs = uvs;
  37148. if (faceColors) {
  37149. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37150. vertexData.colors = totalColors;
  37151. }
  37152. return vertexData;
  37153. };
  37154. /**
  37155. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37156. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37157. * * segments sets the number of horizontal strips optional, default 32
  37158. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37159. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37160. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37161. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37162. * * 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
  37163. * * 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
  37164. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37165. * * 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)
  37166. * * 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)
  37167. * @returns the VertexData of the ellipsoid
  37168. */
  37169. VertexData.CreateSphere = function (options) {
  37170. var segments = options.segments || 32;
  37171. var diameterX = options.diameterX || options.diameter || 1;
  37172. var diameterY = options.diameterY || options.diameter || 1;
  37173. var diameterZ = options.diameterZ || options.diameter || 1;
  37174. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37175. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37176. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37177. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37178. var totalZRotationSteps = 2 + segments;
  37179. var totalYRotationSteps = 2 * totalZRotationSteps;
  37180. var indices = [];
  37181. var positions = [];
  37182. var normals = [];
  37183. var uvs = [];
  37184. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37185. var normalizedZ = zRotationStep / totalZRotationSteps;
  37186. var angleZ = normalizedZ * Math.PI * slice;
  37187. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37188. var normalizedY = yRotationStep / totalYRotationSteps;
  37189. var angleY = normalizedY * Math.PI * 2 * arc;
  37190. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37191. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37192. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37193. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37194. var vertex = complete.multiply(radius);
  37195. var normal = complete.divide(radius).normalize();
  37196. positions.push(vertex.x, vertex.y, vertex.z);
  37197. normals.push(normal.x, normal.y, normal.z);
  37198. uvs.push(normalizedY, normalizedZ);
  37199. }
  37200. if (zRotationStep > 0) {
  37201. var verticesCount = positions.length / 3;
  37202. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37203. indices.push((firstIndex));
  37204. indices.push((firstIndex + 1));
  37205. indices.push(firstIndex + totalYRotationSteps + 1);
  37206. indices.push((firstIndex + totalYRotationSteps + 1));
  37207. indices.push((firstIndex + 1));
  37208. indices.push((firstIndex + totalYRotationSteps + 2));
  37209. }
  37210. }
  37211. }
  37212. // Sides
  37213. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37214. // Result
  37215. var vertexData = new VertexData();
  37216. vertexData.indices = indices;
  37217. vertexData.positions = positions;
  37218. vertexData.normals = normals;
  37219. vertexData.uvs = uvs;
  37220. return vertexData;
  37221. };
  37222. /**
  37223. * Creates the VertexData for a cylinder, cone or prism
  37224. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37225. * * height sets the height (y direction) of the cylinder, optional, default 2
  37226. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37227. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37228. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37229. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37230. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37231. * * 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
  37232. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37233. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37234. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37235. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37236. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37237. * * 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)
  37238. * * 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)
  37239. * @returns the VertexData of the cylinder, cone or prism
  37240. */
  37241. VertexData.CreateCylinder = function (options) {
  37242. var height = options.height || 2;
  37243. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37244. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37245. var tessellation = options.tessellation || 24;
  37246. var subdivisions = options.subdivisions || 1;
  37247. var hasRings = options.hasRings ? true : false;
  37248. var enclose = options.enclose ? true : false;
  37249. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37250. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37251. var faceUV = options.faceUV || new Array(3);
  37252. var faceColors = options.faceColors;
  37253. // default face colors and UV if undefined
  37254. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37255. var ringNb = (hasRings) ? subdivisions : 1;
  37256. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37257. var f;
  37258. for (f = 0; f < surfaceNb; f++) {
  37259. if (faceColors && faceColors[f] === undefined) {
  37260. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37261. }
  37262. }
  37263. for (f = 0; f < surfaceNb; f++) {
  37264. if (faceUV && faceUV[f] === undefined) {
  37265. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37266. }
  37267. }
  37268. var indices = new Array();
  37269. var positions = new Array();
  37270. var normals = new Array();
  37271. var uvs = new Array();
  37272. var colors = new Array();
  37273. var angle_step = Math.PI * 2 * arc / tessellation;
  37274. var angle;
  37275. var h;
  37276. var radius;
  37277. var tan = (diameterBottom - diameterTop) / 2 / height;
  37278. var ringVertex = BABYLON.Vector3.Zero();
  37279. var ringNormal = BABYLON.Vector3.Zero();
  37280. var ringFirstVertex = BABYLON.Vector3.Zero();
  37281. var ringFirstNormal = BABYLON.Vector3.Zero();
  37282. var quadNormal = BABYLON.Vector3.Zero();
  37283. var Y = BABYLON.Axis.Y;
  37284. // positions, normals, uvs
  37285. var i;
  37286. var j;
  37287. var r;
  37288. var ringIdx = 1;
  37289. var s = 1; // surface index
  37290. var cs = 0;
  37291. var v = 0;
  37292. for (i = 0; i <= subdivisions; i++) {
  37293. h = i / subdivisions;
  37294. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37295. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37296. for (r = 0; r < ringIdx; r++) {
  37297. if (hasRings) {
  37298. s += r;
  37299. }
  37300. if (enclose) {
  37301. s += 2 * r;
  37302. }
  37303. for (j = 0; j <= tessellation; j++) {
  37304. angle = j * angle_step;
  37305. // position
  37306. ringVertex.x = Math.cos(-angle) * radius;
  37307. ringVertex.y = -height / 2 + h * height;
  37308. ringVertex.z = Math.sin(-angle) * radius;
  37309. // normal
  37310. if (diameterTop === 0 && i === subdivisions) {
  37311. // if no top cap, reuse former normals
  37312. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37313. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37314. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37315. }
  37316. else {
  37317. ringNormal.x = ringVertex.x;
  37318. ringNormal.z = ringVertex.z;
  37319. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37320. ringNormal.normalize();
  37321. }
  37322. // keep first ring vertex values for enclose
  37323. if (j === 0) {
  37324. ringFirstVertex.copyFrom(ringVertex);
  37325. ringFirstNormal.copyFrom(ringNormal);
  37326. }
  37327. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37328. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37329. if (hasRings) {
  37330. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37331. }
  37332. else {
  37333. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37334. }
  37335. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37336. if (faceColors) {
  37337. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37338. }
  37339. }
  37340. // if enclose, add four vertices and their dedicated normals
  37341. if (arc !== 1 && enclose) {
  37342. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37343. positions.push(0, ringVertex.y, 0);
  37344. positions.push(0, ringVertex.y, 0);
  37345. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37346. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37347. quadNormal.normalize();
  37348. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37349. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37350. quadNormal.normalize();
  37351. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37352. if (hasRings) {
  37353. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37354. }
  37355. else {
  37356. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37357. }
  37358. uvs.push(faceUV[s + 1].x, v);
  37359. uvs.push(faceUV[s + 1].z, v);
  37360. if (hasRings) {
  37361. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37362. }
  37363. else {
  37364. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37365. }
  37366. uvs.push(faceUV[s + 2].x, v);
  37367. uvs.push(faceUV[s + 2].z, v);
  37368. if (faceColors) {
  37369. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37370. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37371. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37372. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37373. }
  37374. }
  37375. if (cs !== s) {
  37376. cs = s;
  37377. }
  37378. }
  37379. }
  37380. // indices
  37381. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37382. var s;
  37383. i = 0;
  37384. for (s = 0; s < subdivisions; s++) {
  37385. var i0 = 0;
  37386. var i1 = 0;
  37387. var i2 = 0;
  37388. var i3 = 0;
  37389. for (j = 0; j < tessellation; j++) {
  37390. i0 = i * (e + 1) + j;
  37391. i1 = (i + 1) * (e + 1) + j;
  37392. i2 = i * (e + 1) + (j + 1);
  37393. i3 = (i + 1) * (e + 1) + (j + 1);
  37394. indices.push(i0, i1, i2);
  37395. indices.push(i3, i2, i1);
  37396. }
  37397. if (arc !== 1 && enclose) { // if enclose, add two quads
  37398. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37399. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37400. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37401. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37402. }
  37403. i = (hasRings) ? (i + 2) : (i + 1);
  37404. }
  37405. // Caps
  37406. var createCylinderCap = function (isTop) {
  37407. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37408. if (radius === 0) {
  37409. return;
  37410. }
  37411. // Cap positions, normals & uvs
  37412. var angle;
  37413. var circleVector;
  37414. var i;
  37415. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37416. var c = null;
  37417. if (faceColors) {
  37418. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37419. }
  37420. // cap center
  37421. var vbase = positions.length / 3;
  37422. var offset = isTop ? height / 2 : -height / 2;
  37423. var center = new BABYLON.Vector3(0, offset, 0);
  37424. positions.push(center.x, center.y, center.z);
  37425. normals.push(0, isTop ? 1 : -1, 0);
  37426. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37427. if (c) {
  37428. colors.push(c.r, c.g, c.b, c.a);
  37429. }
  37430. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37431. for (i = 0; i <= tessellation; i++) {
  37432. angle = Math.PI * 2 * i * arc / tessellation;
  37433. var cos = Math.cos(-angle);
  37434. var sin = Math.sin(-angle);
  37435. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37436. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37437. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37438. normals.push(0, isTop ? 1 : -1, 0);
  37439. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37440. if (c) {
  37441. colors.push(c.r, c.g, c.b, c.a);
  37442. }
  37443. }
  37444. // Cap indices
  37445. for (i = 0; i < tessellation; i++) {
  37446. if (!isTop) {
  37447. indices.push(vbase);
  37448. indices.push(vbase + (i + 1));
  37449. indices.push(vbase + (i + 2));
  37450. }
  37451. else {
  37452. indices.push(vbase);
  37453. indices.push(vbase + (i + 2));
  37454. indices.push(vbase + (i + 1));
  37455. }
  37456. }
  37457. };
  37458. // add caps to geometry
  37459. createCylinderCap(false);
  37460. createCylinderCap(true);
  37461. // Sides
  37462. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37463. var vertexData = new VertexData();
  37464. vertexData.indices = indices;
  37465. vertexData.positions = positions;
  37466. vertexData.normals = normals;
  37467. vertexData.uvs = uvs;
  37468. if (faceColors) {
  37469. vertexData.colors = colors;
  37470. }
  37471. return vertexData;
  37472. };
  37473. /**
  37474. * Creates the VertexData for a torus
  37475. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37476. * * diameter the diameter of the torus, optional default 1
  37477. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37478. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37479. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37480. * * 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)
  37481. * * 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)
  37482. * @returns the VertexData of the torus
  37483. */
  37484. VertexData.CreateTorus = function (options) {
  37485. var indices = [];
  37486. var positions = [];
  37487. var normals = [];
  37488. var uvs = [];
  37489. var diameter = options.diameter || 1;
  37490. var thickness = options.thickness || 0.5;
  37491. var tessellation = options.tessellation || 16;
  37492. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37493. var stride = tessellation + 1;
  37494. for (var i = 0; i <= tessellation; i++) {
  37495. var u = i / tessellation;
  37496. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37497. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37498. for (var j = 0; j <= tessellation; j++) {
  37499. var v = 1 - j / tessellation;
  37500. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37501. var dx = Math.cos(innerAngle);
  37502. var dy = Math.sin(innerAngle);
  37503. // Create a vertex.
  37504. var normal = new BABYLON.Vector3(dx, dy, 0);
  37505. var position = normal.scale(thickness / 2);
  37506. var textureCoordinate = new BABYLON.Vector2(u, v);
  37507. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37508. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37509. positions.push(position.x, position.y, position.z);
  37510. normals.push(normal.x, normal.y, normal.z);
  37511. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37512. // And create indices for two triangles.
  37513. var nextI = (i + 1) % stride;
  37514. var nextJ = (j + 1) % stride;
  37515. indices.push(i * stride + j);
  37516. indices.push(i * stride + nextJ);
  37517. indices.push(nextI * stride + j);
  37518. indices.push(i * stride + nextJ);
  37519. indices.push(nextI * stride + nextJ);
  37520. indices.push(nextI * stride + j);
  37521. }
  37522. }
  37523. // Sides
  37524. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37525. // Result
  37526. var vertexData = new VertexData();
  37527. vertexData.indices = indices;
  37528. vertexData.positions = positions;
  37529. vertexData.normals = normals;
  37530. vertexData.uvs = uvs;
  37531. return vertexData;
  37532. };
  37533. /**
  37534. * Creates the VertexData of the LineSystem
  37535. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37536. * - lines an array of lines, each line being an array of successive Vector3
  37537. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37538. * @returns the VertexData of the LineSystem
  37539. */
  37540. VertexData.CreateLineSystem = function (options) {
  37541. var indices = [];
  37542. var positions = [];
  37543. var lines = options.lines;
  37544. var colors = options.colors;
  37545. var vertexColors = [];
  37546. var idx = 0;
  37547. for (var l = 0; l < lines.length; l++) {
  37548. var points = lines[l];
  37549. for (var index = 0; index < points.length; index++) {
  37550. positions.push(points[index].x, points[index].y, points[index].z);
  37551. if (colors) {
  37552. var color = colors[l];
  37553. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37554. }
  37555. if (index > 0) {
  37556. indices.push(idx - 1);
  37557. indices.push(idx);
  37558. }
  37559. idx++;
  37560. }
  37561. }
  37562. var vertexData = new VertexData();
  37563. vertexData.indices = indices;
  37564. vertexData.positions = positions;
  37565. if (colors) {
  37566. vertexData.colors = vertexColors;
  37567. }
  37568. return vertexData;
  37569. };
  37570. /**
  37571. * Create the VertexData for a DashedLines
  37572. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37573. * - points an array successive Vector3
  37574. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37575. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37576. * - dashNb the intended total number of dashes, optional, default 200
  37577. * @returns the VertexData for the DashedLines
  37578. */
  37579. VertexData.CreateDashedLines = function (options) {
  37580. var dashSize = options.dashSize || 3;
  37581. var gapSize = options.gapSize || 1;
  37582. var dashNb = options.dashNb || 200;
  37583. var points = options.points;
  37584. var positions = new Array();
  37585. var indices = new Array();
  37586. var curvect = BABYLON.Vector3.Zero();
  37587. var lg = 0;
  37588. var nb = 0;
  37589. var shft = 0;
  37590. var dashshft = 0;
  37591. var curshft = 0;
  37592. var idx = 0;
  37593. var i = 0;
  37594. for (i = 0; i < points.length - 1; i++) {
  37595. points[i + 1].subtractToRef(points[i], curvect);
  37596. lg += curvect.length();
  37597. }
  37598. shft = lg / dashNb;
  37599. dashshft = dashSize * shft / (dashSize + gapSize);
  37600. for (i = 0; i < points.length - 1; i++) {
  37601. points[i + 1].subtractToRef(points[i], curvect);
  37602. nb = Math.floor(curvect.length() / shft);
  37603. curvect.normalize();
  37604. for (var j = 0; j < nb; j++) {
  37605. curshft = shft * j;
  37606. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37607. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37608. indices.push(idx, idx + 1);
  37609. idx += 2;
  37610. }
  37611. }
  37612. // Result
  37613. var vertexData = new VertexData();
  37614. vertexData.positions = positions;
  37615. vertexData.indices = indices;
  37616. return vertexData;
  37617. };
  37618. /**
  37619. * Creates the VertexData for a Ground
  37620. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37621. * - width the width (x direction) of the ground, optional, default 1
  37622. * - height the height (z direction) of the ground, optional, default 1
  37623. * - subdivisions the number of subdivisions per side, optional, default 1
  37624. * @returns the VertexData of the Ground
  37625. */
  37626. VertexData.CreateGround = function (options) {
  37627. var indices = [];
  37628. var positions = [];
  37629. var normals = [];
  37630. var uvs = [];
  37631. var row, col;
  37632. var width = options.width || 1;
  37633. var height = options.height || 1;
  37634. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37635. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37636. for (row = 0; row <= subdivisionsY; row++) {
  37637. for (col = 0; col <= subdivisionsX; col++) {
  37638. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37639. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37640. positions.push(position.x, position.y, position.z);
  37641. normals.push(normal.x, normal.y, normal.z);
  37642. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37643. }
  37644. }
  37645. for (row = 0; row < subdivisionsY; row++) {
  37646. for (col = 0; col < subdivisionsX; col++) {
  37647. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37648. indices.push(col + 1 + row * (subdivisionsX + 1));
  37649. indices.push(col + row * (subdivisionsX + 1));
  37650. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37651. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37652. indices.push(col + row * (subdivisionsX + 1));
  37653. }
  37654. }
  37655. // Result
  37656. var vertexData = new VertexData();
  37657. vertexData.indices = indices;
  37658. vertexData.positions = positions;
  37659. vertexData.normals = normals;
  37660. vertexData.uvs = uvs;
  37661. return vertexData;
  37662. };
  37663. /**
  37664. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37665. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37666. * * xmin the ground minimum X coordinate, optional, default -1
  37667. * * zmin the ground minimum Z coordinate, optional, default -1
  37668. * * xmax the ground maximum X coordinate, optional, default 1
  37669. * * zmax the ground maximum Z coordinate, optional, default 1
  37670. * * 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}
  37671. * * 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}
  37672. * @returns the VertexData of the TiledGround
  37673. */
  37674. VertexData.CreateTiledGround = function (options) {
  37675. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37676. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37677. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37678. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37679. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37680. var precision = options.precision || { w: 1, h: 1 };
  37681. var indices = new Array();
  37682. var positions = new Array();
  37683. var normals = new Array();
  37684. var uvs = new Array();
  37685. var row, col, tileRow, tileCol;
  37686. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37687. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37688. precision.w = (precision.w < 1) ? 1 : precision.w;
  37689. precision.h = (precision.h < 1) ? 1 : precision.h;
  37690. var tileSize = {
  37691. 'w': (xmax - xmin) / subdivisions.w,
  37692. 'h': (zmax - zmin) / subdivisions.h
  37693. };
  37694. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37695. // Indices
  37696. var base = positions.length / 3;
  37697. var rowLength = precision.w + 1;
  37698. for (row = 0; row < precision.h; row++) {
  37699. for (col = 0; col < precision.w; col++) {
  37700. var square = [
  37701. base + col + row * rowLength,
  37702. base + (col + 1) + row * rowLength,
  37703. base + (col + 1) + (row + 1) * rowLength,
  37704. base + col + (row + 1) * rowLength
  37705. ];
  37706. indices.push(square[1]);
  37707. indices.push(square[2]);
  37708. indices.push(square[3]);
  37709. indices.push(square[0]);
  37710. indices.push(square[1]);
  37711. indices.push(square[3]);
  37712. }
  37713. }
  37714. // Position, normals and uvs
  37715. var position = BABYLON.Vector3.Zero();
  37716. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37717. for (row = 0; row <= precision.h; row++) {
  37718. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37719. for (col = 0; col <= precision.w; col++) {
  37720. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37721. position.y = 0;
  37722. positions.push(position.x, position.y, position.z);
  37723. normals.push(normal.x, normal.y, normal.z);
  37724. uvs.push(col / precision.w, row / precision.h);
  37725. }
  37726. }
  37727. }
  37728. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37729. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37730. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37731. }
  37732. }
  37733. // Result
  37734. var vertexData = new VertexData();
  37735. vertexData.indices = indices;
  37736. vertexData.positions = positions;
  37737. vertexData.normals = normals;
  37738. vertexData.uvs = uvs;
  37739. return vertexData;
  37740. };
  37741. /**
  37742. * Creates the VertexData of the Ground designed from a heightmap
  37743. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37744. * * width the width (x direction) of the ground
  37745. * * height the height (z direction) of the ground
  37746. * * subdivisions the number of subdivisions per side
  37747. * * minHeight the minimum altitude on the ground, optional, default 0
  37748. * * maxHeight the maximum altitude on the ground, optional default 1
  37749. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37750. * * buffer the array holding the image color data
  37751. * * bufferWidth the width of image
  37752. * * bufferHeight the height of image
  37753. * @returns the VertexData of the Ground designed from a heightmap
  37754. */
  37755. VertexData.CreateGroundFromHeightMap = function (options) {
  37756. var indices = [];
  37757. var positions = [];
  37758. var normals = [];
  37759. var uvs = [];
  37760. var row, col;
  37761. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37762. // Vertices
  37763. for (row = 0; row <= options.subdivisions; row++) {
  37764. for (col = 0; col <= options.subdivisions; col++) {
  37765. 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));
  37766. // Compute height
  37767. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37768. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37769. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37770. var r = options.buffer[pos] / 255.0;
  37771. var g = options.buffer[pos + 1] / 255.0;
  37772. var b = options.buffer[pos + 2] / 255.0;
  37773. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37774. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37775. // Add vertex
  37776. positions.push(position.x, position.y, position.z);
  37777. normals.push(0, 0, 0);
  37778. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37779. }
  37780. }
  37781. // Indices
  37782. for (row = 0; row < options.subdivisions; row++) {
  37783. for (col = 0; col < options.subdivisions; col++) {
  37784. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37785. indices.push(col + 1 + row * (options.subdivisions + 1));
  37786. indices.push(col + row * (options.subdivisions + 1));
  37787. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37788. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37789. indices.push(col + row * (options.subdivisions + 1));
  37790. }
  37791. }
  37792. // Normals
  37793. VertexData.ComputeNormals(positions, indices, normals);
  37794. // Result
  37795. var vertexData = new VertexData();
  37796. vertexData.indices = indices;
  37797. vertexData.positions = positions;
  37798. vertexData.normals = normals;
  37799. vertexData.uvs = uvs;
  37800. return vertexData;
  37801. };
  37802. /**
  37803. * Creates the VertexData for a Plane
  37804. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37805. * * size sets the width and height of the plane to the value of size, optional default 1
  37806. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37807. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37808. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37809. * * 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)
  37810. * * 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)
  37811. * @returns the VertexData of the box
  37812. */
  37813. VertexData.CreatePlane = function (options) {
  37814. var indices = [];
  37815. var positions = [];
  37816. var normals = [];
  37817. var uvs = [];
  37818. var width = options.width || options.size || 1;
  37819. var height = options.height || options.size || 1;
  37820. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37821. // Vertices
  37822. var halfWidth = width / 2.0;
  37823. var halfHeight = height / 2.0;
  37824. positions.push(-halfWidth, -halfHeight, 0);
  37825. normals.push(0, 0, -1.0);
  37826. uvs.push(0.0, 0.0);
  37827. positions.push(halfWidth, -halfHeight, 0);
  37828. normals.push(0, 0, -1.0);
  37829. uvs.push(1.0, 0.0);
  37830. positions.push(halfWidth, halfHeight, 0);
  37831. normals.push(0, 0, -1.0);
  37832. uvs.push(1.0, 1.0);
  37833. positions.push(-halfWidth, halfHeight, 0);
  37834. normals.push(0, 0, -1.0);
  37835. uvs.push(0.0, 1.0);
  37836. // Indices
  37837. indices.push(0);
  37838. indices.push(1);
  37839. indices.push(2);
  37840. indices.push(0);
  37841. indices.push(2);
  37842. indices.push(3);
  37843. // Sides
  37844. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37845. // Result
  37846. var vertexData = new VertexData();
  37847. vertexData.indices = indices;
  37848. vertexData.positions = positions;
  37849. vertexData.normals = normals;
  37850. vertexData.uvs = uvs;
  37851. return vertexData;
  37852. };
  37853. /**
  37854. * Creates the VertexData of the Disc or regular Polygon
  37855. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37856. * * radius the radius of the disc, optional default 0.5
  37857. * * tessellation the number of polygon sides, optional, default 64
  37858. * * 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
  37859. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37860. * * 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)
  37861. * * 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)
  37862. * @returns the VertexData of the box
  37863. */
  37864. VertexData.CreateDisc = function (options) {
  37865. var positions = new Array();
  37866. var indices = new Array();
  37867. var normals = new Array();
  37868. var uvs = new Array();
  37869. var radius = options.radius || 0.5;
  37870. var tessellation = options.tessellation || 64;
  37871. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37872. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37873. // positions and uvs
  37874. positions.push(0, 0, 0); // disc center first
  37875. uvs.push(0.5, 0.5);
  37876. var theta = Math.PI * 2 * arc;
  37877. var step = theta / tessellation;
  37878. for (var a = 0; a < theta; a += step) {
  37879. var x = Math.cos(a);
  37880. var y = Math.sin(a);
  37881. var u = (x + 1) / 2;
  37882. var v = (1 - y) / 2;
  37883. positions.push(radius * x, radius * y, 0);
  37884. uvs.push(u, v);
  37885. }
  37886. if (arc === 1) {
  37887. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37888. uvs.push(uvs[2], uvs[3]);
  37889. }
  37890. //indices
  37891. var vertexNb = positions.length / 3;
  37892. for (var i = 1; i < vertexNb - 1; i++) {
  37893. indices.push(i + 1, 0, i);
  37894. }
  37895. // result
  37896. VertexData.ComputeNormals(positions, indices, normals);
  37897. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37898. var vertexData = new VertexData();
  37899. vertexData.indices = indices;
  37900. vertexData.positions = positions;
  37901. vertexData.normals = normals;
  37902. vertexData.uvs = uvs;
  37903. return vertexData;
  37904. };
  37905. /**
  37906. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37907. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37908. * @param polygon a mesh built from polygonTriangulation.build()
  37909. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37910. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37911. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37912. * @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)
  37913. * @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)
  37914. * @returns the VertexData of the Polygon
  37915. */
  37916. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37917. var faceUV = fUV || new Array(3);
  37918. var faceColors = fColors;
  37919. var colors = [];
  37920. // default face colors and UV if undefined
  37921. for (var f = 0; f < 3; f++) {
  37922. if (faceUV[f] === undefined) {
  37923. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37924. }
  37925. if (faceColors && faceColors[f] === undefined) {
  37926. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37927. }
  37928. }
  37929. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37930. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37931. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37932. var indices = polygon.getIndices();
  37933. // set face colours and textures
  37934. var idx = 0;
  37935. var face = 0;
  37936. for (var index = 0; index < normals.length; index += 3) {
  37937. //Edge Face no. 1
  37938. if (Math.abs(normals[index + 1]) < 0.001) {
  37939. face = 1;
  37940. }
  37941. //Top Face no. 0
  37942. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37943. face = 0;
  37944. }
  37945. //Bottom Face no. 2
  37946. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37947. face = 2;
  37948. }
  37949. idx = index / 3;
  37950. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37951. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37952. if (faceColors) {
  37953. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37954. }
  37955. }
  37956. // sides
  37957. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37958. // Result
  37959. var vertexData = new VertexData();
  37960. vertexData.indices = indices;
  37961. vertexData.positions = positions;
  37962. vertexData.normals = normals;
  37963. vertexData.uvs = uvs;
  37964. if (faceColors) {
  37965. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37966. vertexData.colors = totalColors;
  37967. }
  37968. return vertexData;
  37969. };
  37970. /**
  37971. * Creates the VertexData of the IcoSphere
  37972. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37973. * * radius the radius of the IcoSphere, optional default 1
  37974. * * radiusX allows stretching in the x direction, optional, default radius
  37975. * * radiusY allows stretching in the y direction, optional, default radius
  37976. * * radiusZ allows stretching in the z direction, optional, default radius
  37977. * * flat when true creates a flat shaded mesh, optional, default true
  37978. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37979. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37980. * * 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)
  37981. * * 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)
  37982. * @returns the VertexData of the IcoSphere
  37983. */
  37984. VertexData.CreateIcoSphere = function (options) {
  37985. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37986. var radius = options.radius || 1;
  37987. var flat = (options.flat === undefined) ? true : options.flat;
  37988. var subdivisions = options.subdivisions || 4;
  37989. var radiusX = options.radiusX || radius;
  37990. var radiusY = options.radiusY || radius;
  37991. var radiusZ = options.radiusZ || radius;
  37992. var t = (1 + Math.sqrt(5)) / 2;
  37993. // 12 vertex x,y,z
  37994. var ico_vertices = [
  37995. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37996. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37997. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37998. ];
  37999. // index of 3 vertex makes a face of icopshere
  38000. var ico_indices = [
  38001. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38002. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38003. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38004. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38005. ];
  38006. // vertex for uv have aliased position, not for UV
  38007. var vertices_unalias_id = [
  38008. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38009. // vertex alias
  38010. 0,
  38011. 2,
  38012. 3,
  38013. 3,
  38014. 3,
  38015. 4,
  38016. 7,
  38017. 8,
  38018. 9,
  38019. 9,
  38020. 10,
  38021. 11 // 23: B + 12
  38022. ];
  38023. // uv as integer step (not pixels !)
  38024. var ico_vertexuv = [
  38025. 5, 1, 3, 1, 6, 4, 0, 0,
  38026. 5, 3, 4, 2, 2, 2, 4, 0,
  38027. 2, 0, 1, 1, 6, 0, 6, 2,
  38028. // vertex alias (for same vertex on different faces)
  38029. 0, 4,
  38030. 3, 3,
  38031. 4, 4,
  38032. 3, 1,
  38033. 4, 2,
  38034. 4, 4,
  38035. 0, 2,
  38036. 1, 1,
  38037. 2, 2,
  38038. 3, 3,
  38039. 1, 3,
  38040. 2, 4 // 23: B + 12
  38041. ];
  38042. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38043. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38044. // First island of uv mapping
  38045. // v = 4h 3+ 2
  38046. // v = 3h 9+ 4
  38047. // v = 2h 9+ 5 B
  38048. // v = 1h 9 1 0
  38049. // v = 0h 3 8 7 A
  38050. // u = 0 1 2 3 4 5 6 *a
  38051. // Second island of uv mapping
  38052. // v = 4h 0+ B+ 4+
  38053. // v = 3h A+ 2+
  38054. // v = 2h 7+ 6 3+
  38055. // v = 1h 8+ 3+
  38056. // v = 0h
  38057. // u = 0 1 2 3 4 5 6 *a
  38058. // Face layout on texture UV mapping
  38059. // ============
  38060. // \ 4 /\ 16 / ======
  38061. // \ / \ / /\ 11 /
  38062. // \/ 7 \/ / \ /
  38063. // ======= / 10 \/
  38064. // /\ 17 /\ =======
  38065. // / \ / \ \ 15 /\
  38066. // / 8 \/ 12 \ \ / \
  38067. // ============ \/ 6 \
  38068. // \ 18 /\ ============
  38069. // \ / \ \ 5 /\ 0 /
  38070. // \/ 13 \ \ / \ /
  38071. // ======= \/ 1 \/
  38072. // =============
  38073. // /\ 19 /\ 2 /\
  38074. // / \ / \ / \
  38075. // / 14 \/ 9 \/ 3 \
  38076. // ===================
  38077. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38078. var ustep = 138 / 1024;
  38079. var vstep = 239 / 1024;
  38080. var uoffset = 60 / 1024;
  38081. var voffset = 26 / 1024;
  38082. // Second island should have margin, not to touch the first island
  38083. // avoid any borderline artefact in pixel rounding
  38084. var island_u_offset = -40 / 1024;
  38085. var island_v_offset = +20 / 1024;
  38086. // face is either island 0 or 1 :
  38087. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38088. var island = [
  38089. 0, 0, 0, 0, 1,
  38090. 0, 0, 1, 1, 0,
  38091. 0, 0, 1, 1, 0,
  38092. 0, 1, 1, 1, 0 // 15 - 19
  38093. ];
  38094. var indices = new Array();
  38095. var positions = new Array();
  38096. var normals = new Array();
  38097. var uvs = new Array();
  38098. var current_indice = 0;
  38099. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38100. var face_vertex_pos = new Array(3);
  38101. var face_vertex_uv = new Array(3);
  38102. var v012;
  38103. for (v012 = 0; v012 < 3; v012++) {
  38104. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38105. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38106. }
  38107. // create all with normals
  38108. for (var face = 0; face < 20; face++) {
  38109. // 3 vertex per face
  38110. for (v012 = 0; v012 < 3; v012++) {
  38111. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38112. var v_id = ico_indices[3 * face + v012];
  38113. // vertex have 3D position (x,y,z)
  38114. 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]);
  38115. // Normalize to get normal, then scale to radius
  38116. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38117. // uv Coordinates from vertex ID
  38118. 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);
  38119. }
  38120. // Subdivide the face (interpolate pos, norm, uv)
  38121. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38122. // - norm is linear interpolation of vertex corner normal
  38123. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38124. // - uv is linear interpolation
  38125. //
  38126. // Topology is as below for sub-divide by 2
  38127. // vertex shown as v0,v1,v2
  38128. // interp index is i1 to progress in range [v0,v1[
  38129. // interp index is i2 to progress in range [v0,v2[
  38130. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38131. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38132. //
  38133. //
  38134. // i2 v2
  38135. // ^ ^
  38136. // / / \
  38137. // / / \
  38138. // / / \
  38139. // / / (0,1) \
  38140. // / #---------\
  38141. // / / \ (0,0)'/ \
  38142. // / / \ / \
  38143. // / / \ / \
  38144. // / / (0,0) \ / (1,0) \
  38145. // / #---------#---------\
  38146. // v0 v1
  38147. //
  38148. // --------------------> i1
  38149. //
  38150. // interp of (i1,i2):
  38151. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38152. // along i1 : lerp(x0,x1, i1/(S-i2))
  38153. //
  38154. // centroid of triangle is needed to get help normal computation
  38155. // (c1,c2) are used for centroid location
  38156. var interp_vertex = function (i1, i2, c1, c2) {
  38157. // vertex is interpolated from
  38158. // - face_vertex_pos[0..2]
  38159. // - face_vertex_uv[0..2]
  38160. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38161. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38162. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38163. pos_interp.normalize();
  38164. var vertex_normal;
  38165. if (flat) {
  38166. // in flat mode, recalculate normal as face centroid normal
  38167. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38168. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38169. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38170. }
  38171. else {
  38172. // in smooth mode, recalculate normal from each single vertex position
  38173. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38174. }
  38175. // Vertex normal need correction due to X,Y,Z radius scaling
  38176. vertex_normal.x /= radiusX;
  38177. vertex_normal.y /= radiusY;
  38178. vertex_normal.z /= radiusZ;
  38179. vertex_normal.normalize();
  38180. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38181. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38182. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38183. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38184. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38185. uvs.push(uv_interp.x, uv_interp.y);
  38186. // push each vertex has member of a face
  38187. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38188. indices.push(current_indice);
  38189. current_indice++;
  38190. };
  38191. for (var i2 = 0; i2 < subdivisions; i2++) {
  38192. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38193. // face : (i1,i2) for /\ :
  38194. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38195. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38196. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38197. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38198. if (i1 + i2 + 1 < subdivisions) {
  38199. // face : (i1,i2)' for \/ :
  38200. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38201. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38202. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38203. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38204. }
  38205. }
  38206. }
  38207. }
  38208. // Sides
  38209. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38210. // Result
  38211. var vertexData = new VertexData();
  38212. vertexData.indices = indices;
  38213. vertexData.positions = positions;
  38214. vertexData.normals = normals;
  38215. vertexData.uvs = uvs;
  38216. return vertexData;
  38217. };
  38218. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38219. /**
  38220. * Creates the VertexData for a Polyhedron
  38221. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38222. * * type provided types are:
  38223. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38224. * * 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)
  38225. * * size the size of the IcoSphere, optional default 1
  38226. * * sizeX allows stretching in the x direction, optional, default size
  38227. * * sizeY allows stretching in the y direction, optional, default size
  38228. * * sizeZ allows stretching in the z direction, optional, default size
  38229. * * 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
  38230. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38231. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38232. * * flat when true creates a flat shaded mesh, optional, default true
  38233. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38234. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38235. * * 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)
  38236. * * 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)
  38237. * @returns the VertexData of the Polyhedron
  38238. */
  38239. VertexData.CreatePolyhedron = function (options) {
  38240. // provided polyhedron types :
  38241. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38242. // 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)
  38243. var polyhedra = [];
  38244. 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]] };
  38245. 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]] };
  38246. polyhedra[2] = {
  38247. 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]],
  38248. 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]]
  38249. };
  38250. polyhedra[3] = {
  38251. 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]],
  38252. 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]]
  38253. };
  38254. polyhedra[4] = {
  38255. 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]],
  38256. 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]]
  38257. };
  38258. 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]] };
  38259. 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]] };
  38260. 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]] };
  38261. 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]] };
  38262. 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]] };
  38263. 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]] };
  38264. 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]] };
  38265. 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]] };
  38266. 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]] };
  38267. polyhedra[14] = {
  38268. 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]],
  38269. 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]]
  38270. };
  38271. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38272. var size = options.size;
  38273. var sizeX = options.sizeX || size || 1;
  38274. var sizeY = options.sizeY || size || 1;
  38275. var sizeZ = options.sizeZ || size || 1;
  38276. var data = options.custom || polyhedra[type];
  38277. var nbfaces = data.face.length;
  38278. var faceUV = options.faceUV || new Array(nbfaces);
  38279. var faceColors = options.faceColors;
  38280. var flat = (options.flat === undefined) ? true : options.flat;
  38281. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38282. var positions = new Array();
  38283. var indices = new Array();
  38284. var normals = new Array();
  38285. var uvs = new Array();
  38286. var colors = new Array();
  38287. var index = 0;
  38288. var faceIdx = 0; // face cursor in the array "indexes"
  38289. var indexes = new Array();
  38290. var i = 0;
  38291. var f = 0;
  38292. var u, v, ang, x, y, tmp;
  38293. // default face colors and UV if undefined
  38294. if (flat) {
  38295. for (f = 0; f < nbfaces; f++) {
  38296. if (faceColors && faceColors[f] === undefined) {
  38297. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38298. }
  38299. if (faceUV && faceUV[f] === undefined) {
  38300. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38301. }
  38302. }
  38303. }
  38304. if (!flat) {
  38305. for (i = 0; i < data.vertex.length; i++) {
  38306. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38307. uvs.push(0, 0);
  38308. }
  38309. for (f = 0; f < nbfaces; f++) {
  38310. for (i = 0; i < data.face[f].length - 2; i++) {
  38311. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38312. }
  38313. }
  38314. }
  38315. else {
  38316. for (f = 0; f < nbfaces; f++) {
  38317. var fl = data.face[f].length; // number of vertices of the current face
  38318. ang = 2 * Math.PI / fl;
  38319. x = 0.5 * Math.tan(ang / 2);
  38320. y = 0.5;
  38321. // positions, uvs, colors
  38322. for (i = 0; i < fl; i++) {
  38323. // positions
  38324. 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);
  38325. indexes.push(index);
  38326. index++;
  38327. // uvs
  38328. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38329. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38330. uvs.push(u, v);
  38331. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38332. y = x * Math.sin(ang) + y * Math.cos(ang);
  38333. x = tmp;
  38334. // colors
  38335. if (faceColors) {
  38336. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38337. }
  38338. }
  38339. // indices from indexes
  38340. for (i = 0; i < fl - 2; i++) {
  38341. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38342. }
  38343. faceIdx += fl;
  38344. }
  38345. }
  38346. VertexData.ComputeNormals(positions, indices, normals);
  38347. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38348. var vertexData = new VertexData();
  38349. vertexData.positions = positions;
  38350. vertexData.indices = indices;
  38351. vertexData.normals = normals;
  38352. vertexData.uvs = uvs;
  38353. if (faceColors && flat) {
  38354. vertexData.colors = colors;
  38355. }
  38356. return vertexData;
  38357. };
  38358. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38359. /**
  38360. * Creates the VertexData for a TorusKnot
  38361. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38362. * * radius the radius of the torus knot, optional, default 2
  38363. * * tube the thickness of the tube, optional, default 0.5
  38364. * * radialSegments the number of sides on each tube segments, optional, default 32
  38365. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38366. * * p the number of windings around the z axis, optional, default 2
  38367. * * q the number of windings around the x axis, optional, default 3
  38368. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38369. * * 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)
  38370. * * 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)
  38371. * @returns the VertexData of the Torus Knot
  38372. */
  38373. VertexData.CreateTorusKnot = function (options) {
  38374. var indices = new Array();
  38375. var positions = new Array();
  38376. var normals = new Array();
  38377. var uvs = new Array();
  38378. var radius = options.radius || 2;
  38379. var tube = options.tube || 0.5;
  38380. var radialSegments = options.radialSegments || 32;
  38381. var tubularSegments = options.tubularSegments || 32;
  38382. var p = options.p || 2;
  38383. var q = options.q || 3;
  38384. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38385. // Helper
  38386. var getPos = function (angle) {
  38387. var cu = Math.cos(angle);
  38388. var su = Math.sin(angle);
  38389. var quOverP = q / p * angle;
  38390. var cs = Math.cos(quOverP);
  38391. var tx = radius * (2 + cs) * 0.5 * cu;
  38392. var ty = radius * (2 + cs) * su * 0.5;
  38393. var tz = radius * Math.sin(quOverP) * 0.5;
  38394. return new BABYLON.Vector3(tx, ty, tz);
  38395. };
  38396. // Vertices
  38397. var i;
  38398. var j;
  38399. for (i = 0; i <= radialSegments; i++) {
  38400. var modI = i % radialSegments;
  38401. var u = modI / radialSegments * 2 * p * Math.PI;
  38402. var p1 = getPos(u);
  38403. var p2 = getPos(u + 0.01);
  38404. var tang = p2.subtract(p1);
  38405. var n = p2.add(p1);
  38406. var bitan = BABYLON.Vector3.Cross(tang, n);
  38407. n = BABYLON.Vector3.Cross(bitan, tang);
  38408. bitan.normalize();
  38409. n.normalize();
  38410. for (j = 0; j < tubularSegments; j++) {
  38411. var modJ = j % tubularSegments;
  38412. var v = modJ / tubularSegments * 2 * Math.PI;
  38413. var cx = -tube * Math.cos(v);
  38414. var cy = tube * Math.sin(v);
  38415. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38416. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38417. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38418. uvs.push(i / radialSegments);
  38419. uvs.push(j / tubularSegments);
  38420. }
  38421. }
  38422. for (i = 0; i < radialSegments; i++) {
  38423. for (j = 0; j < tubularSegments; j++) {
  38424. var jNext = (j + 1) % tubularSegments;
  38425. var a = i * tubularSegments + j;
  38426. var b = (i + 1) * tubularSegments + j;
  38427. var c = (i + 1) * tubularSegments + jNext;
  38428. var d = i * tubularSegments + jNext;
  38429. indices.push(d);
  38430. indices.push(b);
  38431. indices.push(a);
  38432. indices.push(d);
  38433. indices.push(c);
  38434. indices.push(b);
  38435. }
  38436. }
  38437. // Normals
  38438. VertexData.ComputeNormals(positions, indices, normals);
  38439. // Sides
  38440. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38441. // Result
  38442. var vertexData = new VertexData();
  38443. vertexData.indices = indices;
  38444. vertexData.positions = positions;
  38445. vertexData.normals = normals;
  38446. vertexData.uvs = uvs;
  38447. return vertexData;
  38448. };
  38449. // Tools
  38450. /**
  38451. * Compute normals for given positions and indices
  38452. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38453. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38454. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38455. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38456. * * facetNormals : optional array of facet normals (vector3)
  38457. * * facetPositions : optional array of facet positions (vector3)
  38458. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38459. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38460. * * bInfo : optional bounding info, required for facetPartitioning computation
  38461. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38462. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38463. * * useRightHandedSystem: optional boolean to for right handed system computation
  38464. * * depthSort : optional boolean to enable the facet depth sort computation
  38465. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38466. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38467. */
  38468. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38469. // temporary scalar variables
  38470. var index = 0; // facet index
  38471. var p1p2x = 0.0; // p1p2 vector x coordinate
  38472. var p1p2y = 0.0; // p1p2 vector y coordinate
  38473. var p1p2z = 0.0; // p1p2 vector z coordinate
  38474. var p3p2x = 0.0; // p3p2 vector x coordinate
  38475. var p3p2y = 0.0; // p3p2 vector y coordinate
  38476. var p3p2z = 0.0; // p3p2 vector z coordinate
  38477. var faceNormalx = 0.0; // facet normal x coordinate
  38478. var faceNormaly = 0.0; // facet normal y coordinate
  38479. var faceNormalz = 0.0; // facet normal z coordinate
  38480. var length = 0.0; // facet normal length before normalization
  38481. var v1x = 0; // vector1 x index in the positions array
  38482. var v1y = 0; // vector1 y index in the positions array
  38483. var v1z = 0; // vector1 z index in the positions array
  38484. var v2x = 0; // vector2 x index in the positions array
  38485. var v2y = 0; // vector2 y index in the positions array
  38486. var v2z = 0; // vector2 z index in the positions array
  38487. var v3x = 0; // vector3 x index in the positions array
  38488. var v3y = 0; // vector3 y index in the positions array
  38489. var v3z = 0; // vector3 z index in the positions array
  38490. var computeFacetNormals = false;
  38491. var computeFacetPositions = false;
  38492. var computeFacetPartitioning = false;
  38493. var computeDepthSort = false;
  38494. var faceNormalSign = 1;
  38495. var ratio = 0;
  38496. var distanceTo = null;
  38497. if (options) {
  38498. computeFacetNormals = (options.facetNormals) ? true : false;
  38499. computeFacetPositions = (options.facetPositions) ? true : false;
  38500. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38501. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38502. ratio = options.ratio || 0;
  38503. computeDepthSort = (options.depthSort) ? true : false;
  38504. distanceTo = (options.distanceTo);
  38505. if (computeDepthSort) {
  38506. if (distanceTo === undefined) {
  38507. distanceTo = BABYLON.Vector3.Zero();
  38508. }
  38509. var depthSortedFacets = options.depthSortedFacets;
  38510. }
  38511. }
  38512. // facetPartitioning reinit if needed
  38513. var xSubRatio = 0;
  38514. var ySubRatio = 0;
  38515. var zSubRatio = 0;
  38516. var subSq = 0;
  38517. if (computeFacetPartitioning && options && options.bbSize) {
  38518. var ox = 0; // X partitioning index for facet position
  38519. var oy = 0; // Y partinioning index for facet position
  38520. var oz = 0; // Z partinioning index for facet position
  38521. var b1x = 0; // X partitioning index for facet v1 vertex
  38522. var b1y = 0; // Y partitioning index for facet v1 vertex
  38523. var b1z = 0; // z partitioning index for facet v1 vertex
  38524. var b2x = 0; // X partitioning index for facet v2 vertex
  38525. var b2y = 0; // Y partitioning index for facet v2 vertex
  38526. var b2z = 0; // Z partitioning index for facet v2 vertex
  38527. var b3x = 0; // X partitioning index for facet v3 vertex
  38528. var b3y = 0; // Y partitioning index for facet v3 vertex
  38529. var b3z = 0; // Z partitioning index for facet v3 vertex
  38530. var block_idx_o = 0; // facet barycenter block index
  38531. var block_idx_v1 = 0; // v1 vertex block index
  38532. var block_idx_v2 = 0; // v2 vertex block index
  38533. var block_idx_v3 = 0; // v3 vertex block index
  38534. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38535. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38536. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38537. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38538. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38539. subSq = options.subDiv.max * options.subDiv.max;
  38540. options.facetPartitioning.length = 0;
  38541. }
  38542. // reset the normals
  38543. for (index = 0; index < positions.length; index++) {
  38544. normals[index] = 0.0;
  38545. }
  38546. // Loop : 1 indice triplet = 1 facet
  38547. var nbFaces = (indices.length / 3) | 0;
  38548. for (index = 0; index < nbFaces; index++) {
  38549. // get the indexes of the coordinates of each vertex of the facet
  38550. v1x = indices[index * 3] * 3;
  38551. v1y = v1x + 1;
  38552. v1z = v1x + 2;
  38553. v2x = indices[index * 3 + 1] * 3;
  38554. v2y = v2x + 1;
  38555. v2z = v2x + 2;
  38556. v3x = indices[index * 3 + 2] * 3;
  38557. v3y = v3x + 1;
  38558. v3z = v3x + 2;
  38559. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38560. p1p2y = positions[v1y] - positions[v2y];
  38561. p1p2z = positions[v1z] - positions[v2z];
  38562. p3p2x = positions[v3x] - positions[v2x];
  38563. p3p2y = positions[v3y] - positions[v2y];
  38564. p3p2z = positions[v3z] - positions[v2z];
  38565. // compute the face normal with the cross product
  38566. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38567. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38568. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38569. // normalize this normal and store it in the array facetData
  38570. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38571. length = (length === 0) ? 1.0 : length;
  38572. faceNormalx /= length;
  38573. faceNormaly /= length;
  38574. faceNormalz /= length;
  38575. if (computeFacetNormals && options) {
  38576. options.facetNormals[index].x = faceNormalx;
  38577. options.facetNormals[index].y = faceNormaly;
  38578. options.facetNormals[index].z = faceNormalz;
  38579. }
  38580. if (computeFacetPositions && options) {
  38581. // compute and the facet barycenter coordinates in the array facetPositions
  38582. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38583. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38584. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38585. }
  38586. if (computeFacetPartitioning && options) {
  38587. // store the facet indexes in arrays in the main facetPartitioning array :
  38588. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38589. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38590. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38591. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38592. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38593. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38594. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38595. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38596. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38597. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38598. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38599. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38600. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38601. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38602. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38603. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38604. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38605. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38606. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38607. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38608. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38609. // push each facet index in each block containing the vertex
  38610. options.facetPartitioning[block_idx_v1].push(index);
  38611. if (block_idx_v2 != block_idx_v1) {
  38612. options.facetPartitioning[block_idx_v2].push(index);
  38613. }
  38614. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38615. options.facetPartitioning[block_idx_v3].push(index);
  38616. }
  38617. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38618. options.facetPartitioning[block_idx_o].push(index);
  38619. }
  38620. }
  38621. if (computeDepthSort && options && options.facetPositions) {
  38622. var dsf = depthSortedFacets[index];
  38623. dsf.ind = index * 3;
  38624. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38625. }
  38626. // compute the normals anyway
  38627. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38628. normals[v1y] += faceNormaly;
  38629. normals[v1z] += faceNormalz;
  38630. normals[v2x] += faceNormalx;
  38631. normals[v2y] += faceNormaly;
  38632. normals[v2z] += faceNormalz;
  38633. normals[v3x] += faceNormalx;
  38634. normals[v3y] += faceNormaly;
  38635. normals[v3z] += faceNormalz;
  38636. }
  38637. // last normalization of each normal
  38638. for (index = 0; index < normals.length / 3; index++) {
  38639. faceNormalx = normals[index * 3];
  38640. faceNormaly = normals[index * 3 + 1];
  38641. faceNormalz = normals[index * 3 + 2];
  38642. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38643. length = (length === 0) ? 1.0 : length;
  38644. faceNormalx /= length;
  38645. faceNormaly /= length;
  38646. faceNormalz /= length;
  38647. normals[index * 3] = faceNormalx;
  38648. normals[index * 3 + 1] = faceNormaly;
  38649. normals[index * 3 + 2] = faceNormalz;
  38650. }
  38651. };
  38652. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38653. var li = indices.length;
  38654. var ln = normals.length;
  38655. var i;
  38656. var n;
  38657. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38658. switch (sideOrientation) {
  38659. case BABYLON.Mesh.FRONTSIDE:
  38660. // nothing changed
  38661. break;
  38662. case BABYLON.Mesh.BACKSIDE:
  38663. var tmp;
  38664. // indices
  38665. for (i = 0; i < li; i += 3) {
  38666. tmp = indices[i];
  38667. indices[i] = indices[i + 2];
  38668. indices[i + 2] = tmp;
  38669. }
  38670. // normals
  38671. for (n = 0; n < ln; n++) {
  38672. normals[n] = -normals[n];
  38673. }
  38674. break;
  38675. case BABYLON.Mesh.DOUBLESIDE:
  38676. // positions
  38677. var lp = positions.length;
  38678. var l = lp / 3;
  38679. for (var p = 0; p < lp; p++) {
  38680. positions[lp + p] = positions[p];
  38681. }
  38682. // indices
  38683. for (i = 0; i < li; i += 3) {
  38684. indices[i + li] = indices[i + 2] + l;
  38685. indices[i + 1 + li] = indices[i + 1] + l;
  38686. indices[i + 2 + li] = indices[i] + l;
  38687. }
  38688. // normals
  38689. for (n = 0; n < ln; n++) {
  38690. normals[ln + n] = -normals[n];
  38691. }
  38692. // uvs
  38693. var lu = uvs.length;
  38694. var u = 0;
  38695. for (u = 0; u < lu; u++) {
  38696. uvs[u + lu] = uvs[u];
  38697. }
  38698. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38699. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38700. u = 0;
  38701. for (i = 0; i < lu / 2; i++) {
  38702. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38703. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38704. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38705. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38706. u += 2;
  38707. }
  38708. break;
  38709. }
  38710. };
  38711. /**
  38712. * Applies VertexData created from the imported parameters to the geometry
  38713. * @param parsedVertexData the parsed data from an imported file
  38714. * @param geometry the geometry to apply the VertexData to
  38715. */
  38716. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38717. var vertexData = new VertexData();
  38718. // positions
  38719. var positions = parsedVertexData.positions;
  38720. if (positions) {
  38721. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38722. }
  38723. // normals
  38724. var normals = parsedVertexData.normals;
  38725. if (normals) {
  38726. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38727. }
  38728. // tangents
  38729. var tangents = parsedVertexData.tangents;
  38730. if (tangents) {
  38731. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38732. }
  38733. // uvs
  38734. var uvs = parsedVertexData.uvs;
  38735. if (uvs) {
  38736. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38737. }
  38738. // uv2s
  38739. var uv2s = parsedVertexData.uv2s;
  38740. if (uv2s) {
  38741. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38742. }
  38743. // uv3s
  38744. var uv3s = parsedVertexData.uv3s;
  38745. if (uv3s) {
  38746. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38747. }
  38748. // uv4s
  38749. var uv4s = parsedVertexData.uv4s;
  38750. if (uv4s) {
  38751. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38752. }
  38753. // uv5s
  38754. var uv5s = parsedVertexData.uv5s;
  38755. if (uv5s) {
  38756. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38757. }
  38758. // uv6s
  38759. var uv6s = parsedVertexData.uv6s;
  38760. if (uv6s) {
  38761. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38762. }
  38763. // colors
  38764. var colors = parsedVertexData.colors;
  38765. if (colors) {
  38766. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38767. }
  38768. // matricesIndices
  38769. var matricesIndices = parsedVertexData.matricesIndices;
  38770. if (matricesIndices) {
  38771. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38772. }
  38773. // matricesWeights
  38774. var matricesWeights = parsedVertexData.matricesWeights;
  38775. if (matricesWeights) {
  38776. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38777. }
  38778. // indices
  38779. var indices = parsedVertexData.indices;
  38780. if (indices) {
  38781. vertexData.indices = indices;
  38782. }
  38783. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38784. };
  38785. return VertexData;
  38786. }());
  38787. BABYLON.VertexData = VertexData;
  38788. })(BABYLON || (BABYLON = {}));
  38789. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38790. var BABYLON;
  38791. (function (BABYLON) {
  38792. /**
  38793. * Class used to store geometry data (vertex buffers + index buffer)
  38794. */
  38795. var Geometry = /** @class */ (function () {
  38796. /**
  38797. * Creates a new geometry
  38798. * @param id defines the unique ID
  38799. * @param scene defines the hosting scene
  38800. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38801. * @param updatable defines if geometry must be updatable (false by default)
  38802. * @param mesh defines the mesh that will be associated with the geometry
  38803. */
  38804. function Geometry(id, scene, vertexData, updatable, mesh) {
  38805. if (updatable === void 0) { updatable = false; }
  38806. if (mesh === void 0) { mesh = null; }
  38807. /**
  38808. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38809. */
  38810. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38811. this._totalVertices = 0;
  38812. this._isDisposed = false;
  38813. this._indexBufferIsUpdatable = false;
  38814. this.id = id;
  38815. this._engine = scene.getEngine();
  38816. this._meshes = [];
  38817. this._scene = scene;
  38818. //Init vertex buffer cache
  38819. this._vertexBuffers = {};
  38820. this._indices = [];
  38821. this._updatable = updatable;
  38822. // vertexData
  38823. if (vertexData) {
  38824. this.setAllVerticesData(vertexData, updatable);
  38825. }
  38826. else {
  38827. this._totalVertices = 0;
  38828. this._indices = [];
  38829. }
  38830. if (this._engine.getCaps().vertexArrayObject) {
  38831. this._vertexArrayObjects = {};
  38832. }
  38833. // applyToMesh
  38834. if (mesh) {
  38835. if (mesh.getClassName() === "LinesMesh") {
  38836. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38837. this._updateExtend();
  38838. }
  38839. this.applyToMesh(mesh);
  38840. mesh.computeWorldMatrix(true);
  38841. }
  38842. }
  38843. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38844. /**
  38845. * 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
  38846. */
  38847. get: function () {
  38848. return this._boundingBias;
  38849. },
  38850. /**
  38851. * 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
  38852. */
  38853. set: function (value) {
  38854. if (this._boundingBias && this._boundingBias.equals(value)) {
  38855. return;
  38856. }
  38857. this._boundingBias = value.clone();
  38858. this._updateBoundingInfo(true, null);
  38859. },
  38860. enumerable: true,
  38861. configurable: true
  38862. });
  38863. /**
  38864. * Static function used to attach a new empty geometry to a mesh
  38865. * @param mesh defines the mesh to attach the geometry to
  38866. * @returns the new {BABYLON.Geometry}
  38867. */
  38868. Geometry.CreateGeometryForMesh = function (mesh) {
  38869. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38870. geometry.applyToMesh(mesh);
  38871. return geometry;
  38872. };
  38873. Object.defineProperty(Geometry.prototype, "extend", {
  38874. /**
  38875. * Gets the current extend of the geometry
  38876. */
  38877. get: function () {
  38878. return this._extend;
  38879. },
  38880. enumerable: true,
  38881. configurable: true
  38882. });
  38883. /**
  38884. * Gets the hosting scene
  38885. * @returns the hosting {BABYLON.Scene}
  38886. */
  38887. Geometry.prototype.getScene = function () {
  38888. return this._scene;
  38889. };
  38890. /**
  38891. * Gets the hosting engine
  38892. * @returns the hosting {BABYLON.Engine}
  38893. */
  38894. Geometry.prototype.getEngine = function () {
  38895. return this._engine;
  38896. };
  38897. /**
  38898. * Defines if the geometry is ready to use
  38899. * @returns true if the geometry is ready to be used
  38900. */
  38901. Geometry.prototype.isReady = function () {
  38902. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38903. };
  38904. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38905. /**
  38906. * Gets a value indicating that the geometry should not be serialized
  38907. */
  38908. get: function () {
  38909. for (var index = 0; index < this._meshes.length; index++) {
  38910. if (!this._meshes[index].doNotSerialize) {
  38911. return false;
  38912. }
  38913. }
  38914. return true;
  38915. },
  38916. enumerable: true,
  38917. configurable: true
  38918. });
  38919. /** @hidden */
  38920. Geometry.prototype._rebuild = function () {
  38921. if (this._vertexArrayObjects) {
  38922. this._vertexArrayObjects = {};
  38923. }
  38924. // Index buffer
  38925. if (this._meshes.length !== 0 && this._indices) {
  38926. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38927. }
  38928. // Vertex buffers
  38929. for (var key in this._vertexBuffers) {
  38930. var vertexBuffer = this._vertexBuffers[key];
  38931. vertexBuffer._rebuild();
  38932. }
  38933. };
  38934. /**
  38935. * Affects all geometry data in one call
  38936. * @param vertexData defines the geometry data
  38937. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38938. */
  38939. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38940. vertexData.applyToGeometry(this, updatable);
  38941. this.notifyUpdate();
  38942. };
  38943. /**
  38944. * Set specific vertex data
  38945. * @param kind defines the data kind (Position, normal, etc...)
  38946. * @param data defines the vertex data to use
  38947. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38948. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38949. */
  38950. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38951. if (updatable === void 0) { updatable = false; }
  38952. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38953. this.setVerticesBuffer(buffer);
  38954. };
  38955. /**
  38956. * Removes a specific vertex data
  38957. * @param kind defines the data kind (Position, normal, etc...)
  38958. */
  38959. Geometry.prototype.removeVerticesData = function (kind) {
  38960. if (this._vertexBuffers[kind]) {
  38961. this._vertexBuffers[kind].dispose();
  38962. delete this._vertexBuffers[kind];
  38963. }
  38964. };
  38965. /**
  38966. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38967. * @param buffer defines the vertex buffer to use
  38968. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38969. */
  38970. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38971. if (totalVertices === void 0) { totalVertices = null; }
  38972. var kind = buffer.getKind();
  38973. if (this._vertexBuffers[kind]) {
  38974. this._vertexBuffers[kind].dispose();
  38975. }
  38976. this._vertexBuffers[kind] = buffer;
  38977. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38978. var data = buffer.getData();
  38979. if (totalVertices != null) {
  38980. this._totalVertices = totalVertices;
  38981. }
  38982. else {
  38983. if (data != null) {
  38984. this._totalVertices = data.length / (buffer.byteStride / 4);
  38985. }
  38986. }
  38987. this._updateExtend(data);
  38988. this._resetPointsArrayCache();
  38989. var meshes = this._meshes;
  38990. var numOfMeshes = meshes.length;
  38991. for (var index = 0; index < numOfMeshes; index++) {
  38992. var mesh = meshes[index];
  38993. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38994. mesh._createGlobalSubMesh(false);
  38995. mesh.computeWorldMatrix(true);
  38996. }
  38997. }
  38998. this.notifyUpdate(kind);
  38999. if (this._vertexArrayObjects) {
  39000. this._disposeVertexArrayObjects();
  39001. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39002. }
  39003. };
  39004. /**
  39005. * Update a specific vertex buffer
  39006. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39007. * It will do nothing if the buffer is not updatable
  39008. * @param kind defines the data kind (Position, normal, etc...)
  39009. * @param data defines the data to use
  39010. * @param offset defines the offset in the target buffer where to store the data
  39011. * @param useBytes set to true if the offset is in bytes
  39012. */
  39013. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39014. if (useBytes === void 0) { useBytes = false; }
  39015. var vertexBuffer = this.getVertexBuffer(kind);
  39016. if (!vertexBuffer) {
  39017. return;
  39018. }
  39019. vertexBuffer.updateDirectly(data, offset, useBytes);
  39020. this.notifyUpdate(kind);
  39021. };
  39022. /**
  39023. * Update a specific vertex buffer
  39024. * This function will create a new buffer if the current one is not updatable
  39025. * @param kind defines the data kind (Position, normal, etc...)
  39026. * @param data defines the data to use
  39027. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39028. */
  39029. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39030. if (updateExtends === void 0) { updateExtends = false; }
  39031. var vertexBuffer = this.getVertexBuffer(kind);
  39032. if (!vertexBuffer) {
  39033. return;
  39034. }
  39035. vertexBuffer.update(data);
  39036. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39037. this._updateBoundingInfo(updateExtends, data);
  39038. }
  39039. this.notifyUpdate(kind);
  39040. };
  39041. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39042. if (updateExtends) {
  39043. this._updateExtend(data);
  39044. }
  39045. var meshes = this._meshes;
  39046. var numOfMeshes = meshes.length;
  39047. this._resetPointsArrayCache();
  39048. for (var index = 0; index < numOfMeshes; index++) {
  39049. var mesh = meshes[index];
  39050. if (updateExtends) {
  39051. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39052. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39053. var subMesh = mesh.subMeshes[subIndex];
  39054. subMesh.refreshBoundingInfo();
  39055. }
  39056. }
  39057. }
  39058. };
  39059. /** @hidden */
  39060. Geometry.prototype._bind = function (effect, indexToBind) {
  39061. if (!effect) {
  39062. return;
  39063. }
  39064. if (indexToBind === undefined) {
  39065. indexToBind = this._indexBuffer;
  39066. }
  39067. var vbs = this.getVertexBuffers();
  39068. if (!vbs) {
  39069. return;
  39070. }
  39071. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39072. this._engine.bindBuffers(vbs, indexToBind, effect);
  39073. return;
  39074. }
  39075. // Using VAO
  39076. if (!this._vertexArrayObjects[effect.key]) {
  39077. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39078. }
  39079. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39080. };
  39081. /**
  39082. * Gets total number of vertices
  39083. * @returns the total number of vertices
  39084. */
  39085. Geometry.prototype.getTotalVertices = function () {
  39086. if (!this.isReady()) {
  39087. return 0;
  39088. }
  39089. return this._totalVertices;
  39090. };
  39091. /**
  39092. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39093. * @param kind defines the data kind (Position, normal, etc...)
  39094. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39095. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39096. * @returns a float array containing vertex data
  39097. */
  39098. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39099. var vertexBuffer = this.getVertexBuffer(kind);
  39100. if (!vertexBuffer) {
  39101. return null;
  39102. }
  39103. var data = vertexBuffer.getData();
  39104. if (!data) {
  39105. return null;
  39106. }
  39107. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39108. var count = this._totalVertices * vertexBuffer.getSize();
  39109. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39110. var copy_1 = new Array(count);
  39111. vertexBuffer.forEach(count, function (value, index) {
  39112. copy_1[index] = value;
  39113. });
  39114. return copy_1;
  39115. }
  39116. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39117. if (data instanceof Array) {
  39118. var offset = vertexBuffer.byteOffset / 4;
  39119. return BABYLON.Tools.Slice(data, offset, offset + count);
  39120. }
  39121. else if (data instanceof ArrayBuffer) {
  39122. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39123. }
  39124. else {
  39125. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39126. }
  39127. }
  39128. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39129. return BABYLON.Tools.Slice(data);
  39130. }
  39131. return data;
  39132. };
  39133. /**
  39134. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39135. * @param kind defines the data kind (Position, normal, etc...)
  39136. * @returns true if the vertex buffer with the specified kind is updatable
  39137. */
  39138. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39139. var vb = this._vertexBuffers[kind];
  39140. if (!vb) {
  39141. return false;
  39142. }
  39143. return vb.isUpdatable();
  39144. };
  39145. /**
  39146. * Gets a specific vertex buffer
  39147. * @param kind defines the data kind (Position, normal, etc...)
  39148. * @returns a {BABYLON.VertexBuffer}
  39149. */
  39150. Geometry.prototype.getVertexBuffer = function (kind) {
  39151. if (!this.isReady()) {
  39152. return null;
  39153. }
  39154. return this._vertexBuffers[kind];
  39155. };
  39156. /**
  39157. * Returns all vertex buffers
  39158. * @return an object holding all vertex buffers indexed by kind
  39159. */
  39160. Geometry.prototype.getVertexBuffers = function () {
  39161. if (!this.isReady()) {
  39162. return null;
  39163. }
  39164. return this._vertexBuffers;
  39165. };
  39166. /**
  39167. * Gets a boolean indicating if specific vertex buffer is present
  39168. * @param kind defines the data kind (Position, normal, etc...)
  39169. * @returns true if data is present
  39170. */
  39171. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39172. if (!this._vertexBuffers) {
  39173. if (this._delayInfo) {
  39174. return this._delayInfo.indexOf(kind) !== -1;
  39175. }
  39176. return false;
  39177. }
  39178. return this._vertexBuffers[kind] !== undefined;
  39179. };
  39180. /**
  39181. * Gets a list of all attached data kinds (Position, normal, etc...)
  39182. * @returns a list of string containing all kinds
  39183. */
  39184. Geometry.prototype.getVerticesDataKinds = function () {
  39185. var result = [];
  39186. var kind;
  39187. if (!this._vertexBuffers && this._delayInfo) {
  39188. for (kind in this._delayInfo) {
  39189. result.push(kind);
  39190. }
  39191. }
  39192. else {
  39193. for (kind in this._vertexBuffers) {
  39194. result.push(kind);
  39195. }
  39196. }
  39197. return result;
  39198. };
  39199. /**
  39200. * Update index buffer
  39201. * @param indices defines the indices to store in the index buffer
  39202. * @param offset defines the offset in the target buffer where to store the data
  39203. */
  39204. Geometry.prototype.updateIndices = function (indices, offset) {
  39205. if (!this._indexBuffer) {
  39206. return;
  39207. }
  39208. if (!this._indexBufferIsUpdatable) {
  39209. this.setIndices(indices, null, true);
  39210. }
  39211. else {
  39212. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39213. }
  39214. };
  39215. /**
  39216. * Creates a new index buffer
  39217. * @param indices defines the indices to store in the index buffer
  39218. * @param totalVertices defines the total number of vertices (could be null)
  39219. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39220. */
  39221. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39222. if (totalVertices === void 0) { totalVertices = null; }
  39223. if (updatable === void 0) { updatable = false; }
  39224. if (this._indexBuffer) {
  39225. this._engine._releaseBuffer(this._indexBuffer);
  39226. }
  39227. this._disposeVertexArrayObjects();
  39228. this._indices = indices;
  39229. this._indexBufferIsUpdatable = updatable;
  39230. if (this._meshes.length !== 0 && this._indices) {
  39231. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39232. }
  39233. if (totalVertices != undefined) { // including null and undefined
  39234. this._totalVertices = totalVertices;
  39235. }
  39236. var meshes = this._meshes;
  39237. var numOfMeshes = meshes.length;
  39238. for (var index = 0; index < numOfMeshes; index++) {
  39239. meshes[index]._createGlobalSubMesh(true);
  39240. }
  39241. this.notifyUpdate();
  39242. };
  39243. /**
  39244. * Return the total number of indices
  39245. * @returns the total number of indices
  39246. */
  39247. Geometry.prototype.getTotalIndices = function () {
  39248. if (!this.isReady()) {
  39249. return 0;
  39250. }
  39251. return this._indices.length;
  39252. };
  39253. /**
  39254. * Gets the index buffer array
  39255. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39256. * @returns the index buffer array
  39257. */
  39258. Geometry.prototype.getIndices = function (copyWhenShared) {
  39259. if (!this.isReady()) {
  39260. return null;
  39261. }
  39262. var orig = this._indices;
  39263. if (!copyWhenShared || this._meshes.length === 1) {
  39264. return orig;
  39265. }
  39266. else {
  39267. var len = orig.length;
  39268. var copy = [];
  39269. for (var i = 0; i < len; i++) {
  39270. copy.push(orig[i]);
  39271. }
  39272. return copy;
  39273. }
  39274. };
  39275. /**
  39276. * Gets the index buffer
  39277. * @return the index buffer
  39278. */
  39279. Geometry.prototype.getIndexBuffer = function () {
  39280. if (!this.isReady()) {
  39281. return null;
  39282. }
  39283. return this._indexBuffer;
  39284. };
  39285. /** @hidden */
  39286. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39287. if (effect === void 0) { effect = null; }
  39288. if (!effect || !this._vertexArrayObjects) {
  39289. return;
  39290. }
  39291. if (this._vertexArrayObjects[effect.key]) {
  39292. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39293. delete this._vertexArrayObjects[effect.key];
  39294. }
  39295. };
  39296. /**
  39297. * Release the associated resources for a specific mesh
  39298. * @param mesh defines the source mesh
  39299. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39300. */
  39301. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39302. var meshes = this._meshes;
  39303. var index = meshes.indexOf(mesh);
  39304. if (index === -1) {
  39305. return;
  39306. }
  39307. meshes.splice(index, 1);
  39308. mesh._geometry = null;
  39309. if (meshes.length === 0 && shouldDispose) {
  39310. this.dispose();
  39311. }
  39312. };
  39313. /**
  39314. * Apply current geometry to a given mesh
  39315. * @param mesh defines the mesh to apply geometry to
  39316. */
  39317. Geometry.prototype.applyToMesh = function (mesh) {
  39318. if (mesh._geometry === this) {
  39319. return;
  39320. }
  39321. var previousGeometry = mesh._geometry;
  39322. if (previousGeometry) {
  39323. previousGeometry.releaseForMesh(mesh);
  39324. }
  39325. var meshes = this._meshes;
  39326. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39327. mesh._geometry = this;
  39328. this._scene.pushGeometry(this);
  39329. meshes.push(mesh);
  39330. if (this.isReady()) {
  39331. this._applyToMesh(mesh);
  39332. }
  39333. else {
  39334. mesh._boundingInfo = this._boundingInfo;
  39335. }
  39336. };
  39337. Geometry.prototype._updateExtend = function (data) {
  39338. if (data === void 0) { data = null; }
  39339. if (!data) {
  39340. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39341. }
  39342. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39343. };
  39344. Geometry.prototype._applyToMesh = function (mesh) {
  39345. var numOfMeshes = this._meshes.length;
  39346. // vertexBuffers
  39347. for (var kind in this._vertexBuffers) {
  39348. if (numOfMeshes === 1) {
  39349. this._vertexBuffers[kind].create();
  39350. }
  39351. var buffer = this._vertexBuffers[kind].getBuffer();
  39352. if (buffer)
  39353. buffer.references = numOfMeshes;
  39354. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39355. if (!this._extend) {
  39356. this._updateExtend();
  39357. }
  39358. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39359. mesh._createGlobalSubMesh(false);
  39360. //bounding info was just created again, world matrix should be applied again.
  39361. mesh._updateBoundingInfo();
  39362. }
  39363. }
  39364. // indexBuffer
  39365. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39366. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39367. }
  39368. if (this._indexBuffer) {
  39369. this._indexBuffer.references = numOfMeshes;
  39370. }
  39371. };
  39372. Geometry.prototype.notifyUpdate = function (kind) {
  39373. if (this.onGeometryUpdated) {
  39374. this.onGeometryUpdated(this, kind);
  39375. }
  39376. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39377. var mesh = _a[_i];
  39378. mesh._markSubMeshesAsAttributesDirty();
  39379. }
  39380. };
  39381. /**
  39382. * Load the geometry if it was flagged as delay loaded
  39383. * @param scene defines the hosting scene
  39384. * @param onLoaded defines a callback called when the geometry is loaded
  39385. */
  39386. Geometry.prototype.load = function (scene, onLoaded) {
  39387. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39388. return;
  39389. }
  39390. if (this.isReady()) {
  39391. if (onLoaded) {
  39392. onLoaded();
  39393. }
  39394. return;
  39395. }
  39396. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39397. this._queueLoad(scene, onLoaded);
  39398. };
  39399. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39400. var _this = this;
  39401. if (!this.delayLoadingFile) {
  39402. return;
  39403. }
  39404. scene._addPendingData(this);
  39405. scene._loadFile(this.delayLoadingFile, function (data) {
  39406. if (!_this._delayLoadingFunction) {
  39407. return;
  39408. }
  39409. _this._delayLoadingFunction(JSON.parse(data), _this);
  39410. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39411. _this._delayInfo = [];
  39412. scene._removePendingData(_this);
  39413. var meshes = _this._meshes;
  39414. var numOfMeshes = meshes.length;
  39415. for (var index = 0; index < numOfMeshes; index++) {
  39416. _this._applyToMesh(meshes[index]);
  39417. }
  39418. if (onLoaded) {
  39419. onLoaded();
  39420. }
  39421. }, undefined, true);
  39422. };
  39423. /**
  39424. * Invert the geometry to move from a right handed system to a left handed one.
  39425. */
  39426. Geometry.prototype.toLeftHanded = function () {
  39427. // Flip faces
  39428. var tIndices = this.getIndices(false);
  39429. if (tIndices != null && tIndices.length > 0) {
  39430. for (var i = 0; i < tIndices.length; i += 3) {
  39431. var tTemp = tIndices[i + 0];
  39432. tIndices[i + 0] = tIndices[i + 2];
  39433. tIndices[i + 2] = tTemp;
  39434. }
  39435. this.setIndices(tIndices);
  39436. }
  39437. // Negate position.z
  39438. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39439. if (tPositions != null && tPositions.length > 0) {
  39440. for (var i = 0; i < tPositions.length; i += 3) {
  39441. tPositions[i + 2] = -tPositions[i + 2];
  39442. }
  39443. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39444. }
  39445. // Negate normal.z
  39446. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39447. if (tNormals != null && tNormals.length > 0) {
  39448. for (var i = 0; i < tNormals.length; i += 3) {
  39449. tNormals[i + 2] = -tNormals[i + 2];
  39450. }
  39451. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39452. }
  39453. };
  39454. // Cache
  39455. /** @hidden */
  39456. Geometry.prototype._resetPointsArrayCache = function () {
  39457. this._positions = null;
  39458. };
  39459. /** @hidden */
  39460. Geometry.prototype._generatePointsArray = function () {
  39461. if (this._positions)
  39462. return true;
  39463. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39464. if (!data || data.length === 0) {
  39465. return false;
  39466. }
  39467. this._positions = [];
  39468. for (var index = 0; index < data.length; index += 3) {
  39469. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39470. }
  39471. return true;
  39472. };
  39473. /**
  39474. * Gets a value indicating if the geometry is disposed
  39475. * @returns true if the geometry was disposed
  39476. */
  39477. Geometry.prototype.isDisposed = function () {
  39478. return this._isDisposed;
  39479. };
  39480. Geometry.prototype._disposeVertexArrayObjects = function () {
  39481. if (this._vertexArrayObjects) {
  39482. for (var kind in this._vertexArrayObjects) {
  39483. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39484. }
  39485. this._vertexArrayObjects = {};
  39486. }
  39487. };
  39488. /**
  39489. * Free all associated resources
  39490. */
  39491. Geometry.prototype.dispose = function () {
  39492. var meshes = this._meshes;
  39493. var numOfMeshes = meshes.length;
  39494. var index;
  39495. for (index = 0; index < numOfMeshes; index++) {
  39496. this.releaseForMesh(meshes[index]);
  39497. }
  39498. this._meshes = [];
  39499. this._disposeVertexArrayObjects();
  39500. for (var kind in this._vertexBuffers) {
  39501. this._vertexBuffers[kind].dispose();
  39502. }
  39503. this._vertexBuffers = {};
  39504. this._totalVertices = 0;
  39505. if (this._indexBuffer) {
  39506. this._engine._releaseBuffer(this._indexBuffer);
  39507. }
  39508. this._indexBuffer = null;
  39509. this._indices = [];
  39510. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39511. this.delayLoadingFile = null;
  39512. this._delayLoadingFunction = null;
  39513. this._delayInfo = [];
  39514. this._boundingInfo = null;
  39515. this._scene.removeGeometry(this);
  39516. this._isDisposed = true;
  39517. };
  39518. /**
  39519. * Clone the current geometry into a new geometry
  39520. * @param id defines the unique ID of the new geometry
  39521. * @returns a new geometry object
  39522. */
  39523. Geometry.prototype.copy = function (id) {
  39524. var vertexData = new BABYLON.VertexData();
  39525. vertexData.indices = [];
  39526. var indices = this.getIndices();
  39527. if (indices) {
  39528. for (var index = 0; index < indices.length; index++) {
  39529. vertexData.indices.push(indices[index]);
  39530. }
  39531. }
  39532. var updatable = false;
  39533. var stopChecking = false;
  39534. var kind;
  39535. for (kind in this._vertexBuffers) {
  39536. // using slice() to make a copy of the array and not just reference it
  39537. var data = this.getVerticesData(kind);
  39538. if (data instanceof Float32Array) {
  39539. vertexData.set(new Float32Array(data), kind);
  39540. }
  39541. else {
  39542. vertexData.set(data.slice(0), kind);
  39543. }
  39544. if (!stopChecking) {
  39545. var vb = this.getVertexBuffer(kind);
  39546. if (vb) {
  39547. updatable = vb.isUpdatable();
  39548. stopChecking = !updatable;
  39549. }
  39550. }
  39551. }
  39552. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39553. geometry.delayLoadState = this.delayLoadState;
  39554. geometry.delayLoadingFile = this.delayLoadingFile;
  39555. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39556. for (kind in this._delayInfo) {
  39557. geometry._delayInfo = geometry._delayInfo || [];
  39558. geometry._delayInfo.push(kind);
  39559. }
  39560. // Bounding info
  39561. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39562. return geometry;
  39563. };
  39564. /**
  39565. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39566. * @return a JSON representation of the current geometry data (without the vertices data)
  39567. */
  39568. Geometry.prototype.serialize = function () {
  39569. var serializationObject = {};
  39570. serializationObject.id = this.id;
  39571. serializationObject.updatable = this._updatable;
  39572. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39573. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39574. }
  39575. return serializationObject;
  39576. };
  39577. Geometry.prototype.toNumberArray = function (origin) {
  39578. if (Array.isArray(origin)) {
  39579. return origin;
  39580. }
  39581. else {
  39582. return Array.prototype.slice.call(origin);
  39583. }
  39584. };
  39585. /**
  39586. * Serialize all vertices data into a JSON oject
  39587. * @returns a JSON representation of the current geometry data
  39588. */
  39589. Geometry.prototype.serializeVerticeData = function () {
  39590. var serializationObject = this.serialize();
  39591. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39592. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39593. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39594. serializationObject.positions._updatable = true;
  39595. }
  39596. }
  39597. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39598. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39599. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39600. serializationObject.normals._updatable = true;
  39601. }
  39602. }
  39603. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39604. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39605. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39606. serializationObject.tangets._updatable = true;
  39607. }
  39608. }
  39609. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39610. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39611. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39612. serializationObject.uvs._updatable = true;
  39613. }
  39614. }
  39615. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39616. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39617. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39618. serializationObject.uv2s._updatable = true;
  39619. }
  39620. }
  39621. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39622. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39623. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39624. serializationObject.uv3s._updatable = true;
  39625. }
  39626. }
  39627. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39628. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39629. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39630. serializationObject.uv4s._updatable = true;
  39631. }
  39632. }
  39633. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39634. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39635. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39636. serializationObject.uv5s._updatable = true;
  39637. }
  39638. }
  39639. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39640. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39641. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39642. serializationObject.uv6s._updatable = true;
  39643. }
  39644. }
  39645. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39646. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39647. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39648. serializationObject.colors._updatable = true;
  39649. }
  39650. }
  39651. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39652. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39653. serializationObject.matricesIndices._isExpanded = true;
  39654. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39655. serializationObject.matricesIndices._updatable = true;
  39656. }
  39657. }
  39658. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39659. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39660. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39661. serializationObject.matricesWeights._updatable = true;
  39662. }
  39663. }
  39664. serializationObject.indices = this.toNumberArray(this.getIndices());
  39665. return serializationObject;
  39666. };
  39667. // Statics
  39668. /**
  39669. * Extracts a clone of a mesh geometry
  39670. * @param mesh defines the source mesh
  39671. * @param id defines the unique ID of the new geometry object
  39672. * @returns the new geometry object
  39673. */
  39674. Geometry.ExtractFromMesh = function (mesh, id) {
  39675. var geometry = mesh._geometry;
  39676. if (!geometry) {
  39677. return null;
  39678. }
  39679. return geometry.copy(id);
  39680. };
  39681. /**
  39682. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39683. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39684. * Be aware Math.random() could cause collisions, but:
  39685. * "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"
  39686. * @returns a string containing a new GUID
  39687. */
  39688. Geometry.RandomId = function () {
  39689. return BABYLON.Tools.RandomId();
  39690. };
  39691. /** @hidden */
  39692. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39693. var scene = mesh.getScene();
  39694. // Geometry
  39695. var geometryId = parsedGeometry.geometryId;
  39696. if (geometryId) {
  39697. var geometry = scene.getGeometryByID(geometryId);
  39698. if (geometry) {
  39699. geometry.applyToMesh(mesh);
  39700. }
  39701. }
  39702. else if (parsedGeometry instanceof ArrayBuffer) {
  39703. var binaryInfo = mesh._binaryInfo;
  39704. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39705. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39706. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39707. }
  39708. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39709. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39710. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39711. }
  39712. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39713. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39714. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39715. }
  39716. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39717. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39718. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39719. }
  39720. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39721. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39722. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39723. }
  39724. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39725. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39726. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39727. }
  39728. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39729. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39730. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39731. }
  39732. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39733. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39734. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39735. }
  39736. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39737. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39738. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39739. }
  39740. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39741. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39742. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39743. }
  39744. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39745. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39746. var floatIndices = [];
  39747. for (var i = 0; i < matricesIndicesData.length; i++) {
  39748. var index = matricesIndicesData[i];
  39749. floatIndices.push(index & 0x000000FF);
  39750. floatIndices.push((index & 0x0000FF00) >> 8);
  39751. floatIndices.push((index & 0x00FF0000) >> 16);
  39752. floatIndices.push(index >> 24);
  39753. }
  39754. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39755. }
  39756. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39757. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39758. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39759. }
  39760. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39761. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39762. mesh.setIndices(indicesData, null);
  39763. }
  39764. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39765. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39766. mesh.subMeshes = [];
  39767. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39768. var materialIndex = subMeshesData[(i * 5) + 0];
  39769. var verticesStart = subMeshesData[(i * 5) + 1];
  39770. var verticesCount = subMeshesData[(i * 5) + 2];
  39771. var indexStart = subMeshesData[(i * 5) + 3];
  39772. var indexCount = subMeshesData[(i * 5) + 4];
  39773. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39774. }
  39775. }
  39776. }
  39777. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39778. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39779. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39780. if (parsedGeometry.tangents) {
  39781. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39782. }
  39783. if (parsedGeometry.uvs) {
  39784. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39785. }
  39786. if (parsedGeometry.uvs2) {
  39787. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39788. }
  39789. if (parsedGeometry.uvs3) {
  39790. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39791. }
  39792. if (parsedGeometry.uvs4) {
  39793. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39794. }
  39795. if (parsedGeometry.uvs5) {
  39796. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39797. }
  39798. if (parsedGeometry.uvs6) {
  39799. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39800. }
  39801. if (parsedGeometry.colors) {
  39802. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39803. }
  39804. if (parsedGeometry.matricesIndices) {
  39805. if (!parsedGeometry.matricesIndices._isExpanded) {
  39806. var floatIndices = [];
  39807. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39808. var matricesIndex = parsedGeometry.matricesIndices[i];
  39809. floatIndices.push(matricesIndex & 0x000000FF);
  39810. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39811. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39812. floatIndices.push(matricesIndex >> 24);
  39813. }
  39814. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39815. }
  39816. else {
  39817. delete parsedGeometry.matricesIndices._isExpanded;
  39818. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39819. }
  39820. }
  39821. if (parsedGeometry.matricesIndicesExtra) {
  39822. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39823. var floatIndices = [];
  39824. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39825. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39826. floatIndices.push(matricesIndex & 0x000000FF);
  39827. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39828. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39829. floatIndices.push(matricesIndex >> 24);
  39830. }
  39831. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39832. }
  39833. else {
  39834. delete parsedGeometry.matricesIndices._isExpanded;
  39835. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39836. }
  39837. }
  39838. if (parsedGeometry.matricesWeights) {
  39839. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39840. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39841. }
  39842. if (parsedGeometry.matricesWeightsExtra) {
  39843. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39844. }
  39845. mesh.setIndices(parsedGeometry.indices, null);
  39846. }
  39847. // SubMeshes
  39848. if (parsedGeometry.subMeshes) {
  39849. mesh.subMeshes = [];
  39850. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39851. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39852. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39853. }
  39854. }
  39855. // Flat shading
  39856. if (mesh._shouldGenerateFlatShading) {
  39857. mesh.convertToFlatShadedMesh();
  39858. delete mesh._shouldGenerateFlatShading;
  39859. }
  39860. // Update
  39861. mesh.computeWorldMatrix(true);
  39862. // Octree
  39863. var sceneOctree = scene.selectionOctree;
  39864. if (sceneOctree !== undefined && sceneOctree !== null) {
  39865. sceneOctree.addMesh(mesh);
  39866. }
  39867. };
  39868. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39869. var epsilon = 1e-3;
  39870. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39871. return;
  39872. }
  39873. var noInfluenceBoneIndex = 0.0;
  39874. if (parsedGeometry.skeletonId > -1) {
  39875. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39876. if (!skeleton) {
  39877. return;
  39878. }
  39879. noInfluenceBoneIndex = skeleton.bones.length;
  39880. }
  39881. else {
  39882. return;
  39883. }
  39884. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39885. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39886. var matricesWeights = parsedGeometry.matricesWeights;
  39887. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39888. var influencers = parsedGeometry.numBoneInfluencer;
  39889. var size = matricesWeights.length;
  39890. for (var i = 0; i < size; i += 4) {
  39891. var weight = 0.0;
  39892. var firstZeroWeight = -1;
  39893. for (var j = 0; j < 4; j++) {
  39894. var w = matricesWeights[i + j];
  39895. weight += w;
  39896. if (w < epsilon && firstZeroWeight < 0) {
  39897. firstZeroWeight = j;
  39898. }
  39899. }
  39900. if (matricesWeightsExtra) {
  39901. for (var j = 0; j < 4; j++) {
  39902. var w = matricesWeightsExtra[i + j];
  39903. weight += w;
  39904. if (w < epsilon && firstZeroWeight < 0) {
  39905. firstZeroWeight = j + 4;
  39906. }
  39907. }
  39908. }
  39909. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39910. firstZeroWeight = influencers - 1;
  39911. }
  39912. if (weight > epsilon) {
  39913. var mweight = 1.0 / weight;
  39914. for (var j = 0; j < 4; j++) {
  39915. matricesWeights[i + j] *= mweight;
  39916. }
  39917. if (matricesWeightsExtra) {
  39918. for (var j = 0; j < 4; j++) {
  39919. matricesWeightsExtra[i + j] *= mweight;
  39920. }
  39921. }
  39922. }
  39923. else {
  39924. if (firstZeroWeight >= 4) {
  39925. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39926. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39927. }
  39928. else {
  39929. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39930. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39931. }
  39932. }
  39933. }
  39934. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39935. if (parsedGeometry.matricesWeightsExtra) {
  39936. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39937. }
  39938. };
  39939. /**
  39940. * Create a new geometry from persisted data (Using .babylon file format)
  39941. * @param parsedVertexData defines the persisted data
  39942. * @param scene defines the hosting scene
  39943. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39944. * @returns the new geometry object
  39945. */
  39946. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39947. if (scene.getGeometryByID(parsedVertexData.id)) {
  39948. return null; // null since geometry could be something else than a box...
  39949. }
  39950. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39951. if (BABYLON.Tags) {
  39952. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39953. }
  39954. if (parsedVertexData.delayLoadingFile) {
  39955. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39956. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39957. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39958. geometry._delayInfo = [];
  39959. if (parsedVertexData.hasUVs) {
  39960. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39961. }
  39962. if (parsedVertexData.hasUVs2) {
  39963. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39964. }
  39965. if (parsedVertexData.hasUVs3) {
  39966. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39967. }
  39968. if (parsedVertexData.hasUVs4) {
  39969. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39970. }
  39971. if (parsedVertexData.hasUVs5) {
  39972. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39973. }
  39974. if (parsedVertexData.hasUVs6) {
  39975. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39976. }
  39977. if (parsedVertexData.hasColors) {
  39978. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39979. }
  39980. if (parsedVertexData.hasMatricesIndices) {
  39981. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39982. }
  39983. if (parsedVertexData.hasMatricesWeights) {
  39984. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39985. }
  39986. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39987. }
  39988. else {
  39989. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39990. }
  39991. scene.pushGeometry(geometry, true);
  39992. return geometry;
  39993. };
  39994. return Geometry;
  39995. }());
  39996. BABYLON.Geometry = Geometry;
  39997. // Primitives
  39998. /// Abstract class
  39999. /**
  40000. * Abstract class used to provide common services for all typed geometries
  40001. * @hidden
  40002. */
  40003. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40004. __extends(_PrimitiveGeometry, _super);
  40005. /**
  40006. * Creates a new typed geometry
  40007. * @param id defines the unique ID of the geometry
  40008. * @param scene defines the hosting scene
  40009. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40010. * @param mesh defines the hosting mesh (can be null)
  40011. */
  40012. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40013. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40014. if (mesh === void 0) { mesh = null; }
  40015. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40016. _this._canBeRegenerated = _canBeRegenerated;
  40017. _this._beingRegenerated = true;
  40018. _this.regenerate();
  40019. _this._beingRegenerated = false;
  40020. return _this;
  40021. }
  40022. /**
  40023. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40024. * @returns true if the geometry can be regenerated
  40025. */
  40026. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40027. return this._canBeRegenerated;
  40028. };
  40029. /**
  40030. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40031. */
  40032. _PrimitiveGeometry.prototype.regenerate = function () {
  40033. if (!this._canBeRegenerated) {
  40034. return;
  40035. }
  40036. this._beingRegenerated = true;
  40037. this.setAllVerticesData(this._regenerateVertexData(), false);
  40038. this._beingRegenerated = false;
  40039. };
  40040. /**
  40041. * Clone the geometry
  40042. * @param id defines the unique ID of the new geometry
  40043. * @returns the new geometry
  40044. */
  40045. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40046. return _super.prototype.copy.call(this, id);
  40047. };
  40048. // overrides
  40049. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40050. if (!this._beingRegenerated) {
  40051. return;
  40052. }
  40053. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40054. };
  40055. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40056. if (!this._beingRegenerated) {
  40057. return;
  40058. }
  40059. _super.prototype.setVerticesData.call(this, kind, data, false);
  40060. };
  40061. // to override
  40062. /** @hidden */
  40063. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40064. throw new Error("Abstract method");
  40065. };
  40066. _PrimitiveGeometry.prototype.copy = function (id) {
  40067. throw new Error("Must be overriden in sub-classes.");
  40068. };
  40069. _PrimitiveGeometry.prototype.serialize = function () {
  40070. var serializationObject = _super.prototype.serialize.call(this);
  40071. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40072. return serializationObject;
  40073. };
  40074. return _PrimitiveGeometry;
  40075. }(Geometry));
  40076. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40077. /**
  40078. * Creates a ribbon geometry
  40079. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40080. */
  40081. var RibbonGeometry = /** @class */ (function (_super) {
  40082. __extends(RibbonGeometry, _super);
  40083. /**
  40084. * Creates a ribbon geometry
  40085. * @param id defines the unique ID of the geometry
  40086. * @param scene defines the hosting scene
  40087. * @param pathArray defines the array of paths to use
  40088. * @param closeArray defines if the last path and the first path must be joined
  40089. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40090. * @param offset defines the offset between points
  40091. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40092. * @param mesh defines the hosting mesh (can be null)
  40093. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40094. */
  40095. function RibbonGeometry(id, scene,
  40096. /**
  40097. * Defines the array of paths to use
  40098. */
  40099. pathArray,
  40100. /**
  40101. * Defines if the last and first points of each path in your pathArray must be joined
  40102. */
  40103. closeArray,
  40104. /**
  40105. * Defines if the last and first points of each path in your pathArray must be joined
  40106. */
  40107. closePath,
  40108. /**
  40109. * Defines the offset between points
  40110. */
  40111. offset, canBeRegenerated, mesh,
  40112. /**
  40113. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40114. */
  40115. side) {
  40116. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40117. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40118. _this.pathArray = pathArray;
  40119. _this.closeArray = closeArray;
  40120. _this.closePath = closePath;
  40121. _this.offset = offset;
  40122. _this.side = side;
  40123. return _this;
  40124. }
  40125. /** @hidden */
  40126. RibbonGeometry.prototype._regenerateVertexData = function () {
  40127. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40128. };
  40129. RibbonGeometry.prototype.copy = function (id) {
  40130. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40131. };
  40132. return RibbonGeometry;
  40133. }(_PrimitiveGeometry));
  40134. BABYLON.RibbonGeometry = RibbonGeometry;
  40135. /**
  40136. * Creates a box geometry
  40137. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40138. */
  40139. var BoxGeometry = /** @class */ (function (_super) {
  40140. __extends(BoxGeometry, _super);
  40141. /**
  40142. * Creates a box geometry
  40143. * @param id defines the unique ID of the geometry
  40144. * @param scene defines the hosting scene
  40145. * @param size defines the zise of the box (width, height and depth are the same)
  40146. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40147. * @param mesh defines the hosting mesh (can be null)
  40148. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40149. */
  40150. function BoxGeometry(id, scene,
  40151. /**
  40152. * Defines the zise of the box (width, height and depth are the same)
  40153. */
  40154. size, canBeRegenerated, mesh,
  40155. /**
  40156. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40157. */
  40158. side) {
  40159. if (mesh === void 0) { mesh = null; }
  40160. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40161. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40162. _this.size = size;
  40163. _this.side = side;
  40164. return _this;
  40165. }
  40166. BoxGeometry.prototype._regenerateVertexData = function () {
  40167. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40168. };
  40169. BoxGeometry.prototype.copy = function (id) {
  40170. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40171. };
  40172. BoxGeometry.prototype.serialize = function () {
  40173. var serializationObject = _super.prototype.serialize.call(this);
  40174. serializationObject.size = this.size;
  40175. return serializationObject;
  40176. };
  40177. BoxGeometry.Parse = function (parsedBox, scene) {
  40178. if (scene.getGeometryByID(parsedBox.id)) {
  40179. return null; // null since geometry could be something else than a box...
  40180. }
  40181. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40182. if (BABYLON.Tags) {
  40183. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40184. }
  40185. scene.pushGeometry(box, true);
  40186. return box;
  40187. };
  40188. return BoxGeometry;
  40189. }(_PrimitiveGeometry));
  40190. BABYLON.BoxGeometry = BoxGeometry;
  40191. /**
  40192. * Creates a sphere geometry
  40193. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40194. */
  40195. var SphereGeometry = /** @class */ (function (_super) {
  40196. __extends(SphereGeometry, _super);
  40197. /**
  40198. * Create a new sphere geometry
  40199. * @param id defines the unique ID of the geometry
  40200. * @param scene defines the hosting scene
  40201. * @param segments defines the number of segments to use to create the sphere
  40202. * @param diameter defines the diameter of the sphere
  40203. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40204. * @param mesh defines the hosting mesh (can be null)
  40205. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40206. */
  40207. function SphereGeometry(id, scene,
  40208. /**
  40209. * Defines the number of segments to use to create the sphere
  40210. */
  40211. segments,
  40212. /**
  40213. * Defines the diameter of the sphere
  40214. */
  40215. diameter, canBeRegenerated, mesh,
  40216. /**
  40217. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40218. */
  40219. side) {
  40220. if (mesh === void 0) { mesh = null; }
  40221. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40222. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40223. _this.segments = segments;
  40224. _this.diameter = diameter;
  40225. _this.side = side;
  40226. return _this;
  40227. }
  40228. SphereGeometry.prototype._regenerateVertexData = function () {
  40229. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40230. };
  40231. SphereGeometry.prototype.copy = function (id) {
  40232. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40233. };
  40234. SphereGeometry.prototype.serialize = function () {
  40235. var serializationObject = _super.prototype.serialize.call(this);
  40236. serializationObject.segments = this.segments;
  40237. serializationObject.diameter = this.diameter;
  40238. return serializationObject;
  40239. };
  40240. SphereGeometry.Parse = function (parsedSphere, scene) {
  40241. if (scene.getGeometryByID(parsedSphere.id)) {
  40242. return null; // null since geometry could be something else than a sphere...
  40243. }
  40244. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40245. if (BABYLON.Tags) {
  40246. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40247. }
  40248. scene.pushGeometry(sphere, true);
  40249. return sphere;
  40250. };
  40251. return SphereGeometry;
  40252. }(_PrimitiveGeometry));
  40253. BABYLON.SphereGeometry = SphereGeometry;
  40254. /**
  40255. * Creates a disc geometry
  40256. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40257. */
  40258. var DiscGeometry = /** @class */ (function (_super) {
  40259. __extends(DiscGeometry, _super);
  40260. /**
  40261. * Creates a new disc geometry
  40262. * @param id defines the unique ID of the geometry
  40263. * @param scene defines the hosting scene
  40264. * @param radius defines the radius of the disc
  40265. * @param tessellation defines the tesselation factor to apply to the disc
  40266. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40267. * @param mesh defines the hosting mesh (can be null)
  40268. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40269. */
  40270. function DiscGeometry(id, scene,
  40271. /**
  40272. * Defines the radius of the disc
  40273. */
  40274. radius,
  40275. /**
  40276. * Defines the tesselation factor to apply to the disc
  40277. */
  40278. tessellation, canBeRegenerated, mesh,
  40279. /**
  40280. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40281. */
  40282. side) {
  40283. if (mesh === void 0) { mesh = null; }
  40284. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40285. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40286. _this.radius = radius;
  40287. _this.tessellation = tessellation;
  40288. _this.side = side;
  40289. return _this;
  40290. }
  40291. DiscGeometry.prototype._regenerateVertexData = function () {
  40292. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40293. };
  40294. DiscGeometry.prototype.copy = function (id) {
  40295. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40296. };
  40297. return DiscGeometry;
  40298. }(_PrimitiveGeometry));
  40299. BABYLON.DiscGeometry = DiscGeometry;
  40300. /**
  40301. * Creates a new cylinder geometry
  40302. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40303. */
  40304. var CylinderGeometry = /** @class */ (function (_super) {
  40305. __extends(CylinderGeometry, _super);
  40306. /**
  40307. * Creates a new cylinder geometry
  40308. * @param id defines the unique ID of the geometry
  40309. * @param scene defines the hosting scene
  40310. * @param height defines the height of the cylinder
  40311. * @param diameterTop defines the diameter of the cylinder's top cap
  40312. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40313. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40314. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40315. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40316. * @param mesh defines the hosting mesh (can be null)
  40317. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40318. */
  40319. function CylinderGeometry(id, scene,
  40320. /**
  40321. * Defines the height of the cylinder
  40322. */
  40323. height,
  40324. /**
  40325. * Defines the diameter of the cylinder's top cap
  40326. */
  40327. diameterTop,
  40328. /**
  40329. * Defines the diameter of the cylinder's bottom cap
  40330. */
  40331. diameterBottom,
  40332. /**
  40333. * Defines the tessellation factor to apply to the cylinder
  40334. */
  40335. tessellation,
  40336. /**
  40337. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40338. */
  40339. subdivisions, canBeRegenerated, mesh,
  40340. /**
  40341. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40342. */
  40343. side) {
  40344. if (subdivisions === void 0) { subdivisions = 1; }
  40345. if (mesh === void 0) { mesh = null; }
  40346. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40347. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40348. _this.height = height;
  40349. _this.diameterTop = diameterTop;
  40350. _this.diameterBottom = diameterBottom;
  40351. _this.tessellation = tessellation;
  40352. _this.subdivisions = subdivisions;
  40353. _this.side = side;
  40354. return _this;
  40355. }
  40356. CylinderGeometry.prototype._regenerateVertexData = function () {
  40357. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40358. };
  40359. CylinderGeometry.prototype.copy = function (id) {
  40360. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40361. };
  40362. CylinderGeometry.prototype.serialize = function () {
  40363. var serializationObject = _super.prototype.serialize.call(this);
  40364. serializationObject.height = this.height;
  40365. serializationObject.diameterTop = this.diameterTop;
  40366. serializationObject.diameterBottom = this.diameterBottom;
  40367. serializationObject.tessellation = this.tessellation;
  40368. return serializationObject;
  40369. };
  40370. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40371. if (scene.getGeometryByID(parsedCylinder.id)) {
  40372. return null; // null since geometry could be something else than a cylinder...
  40373. }
  40374. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40375. if (BABYLON.Tags) {
  40376. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40377. }
  40378. scene.pushGeometry(cylinder, true);
  40379. return cylinder;
  40380. };
  40381. return CylinderGeometry;
  40382. }(_PrimitiveGeometry));
  40383. BABYLON.CylinderGeometry = CylinderGeometry;
  40384. /**
  40385. * Creates a new torus geometry
  40386. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40387. */
  40388. var TorusGeometry = /** @class */ (function (_super) {
  40389. __extends(TorusGeometry, _super);
  40390. /**
  40391. * Creates a new torus geometry
  40392. * @param id defines the unique ID of the geometry
  40393. * @param scene defines the hosting scene
  40394. * @param diameter defines the diameter of the torus
  40395. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40396. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40397. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40398. * @param mesh defines the hosting mesh (can be null)
  40399. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40400. */
  40401. function TorusGeometry(id, scene,
  40402. /**
  40403. * Defines the diameter of the torus
  40404. */
  40405. diameter,
  40406. /**
  40407. * Defines the thickness of the torus (ie. internal diameter)
  40408. */
  40409. thickness,
  40410. /**
  40411. * Defines the tesselation factor to apply to the torus
  40412. */
  40413. tessellation, canBeRegenerated, mesh,
  40414. /**
  40415. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40416. */
  40417. side) {
  40418. if (mesh === void 0) { mesh = null; }
  40419. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40420. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40421. _this.diameter = diameter;
  40422. _this.thickness = thickness;
  40423. _this.tessellation = tessellation;
  40424. _this.side = side;
  40425. return _this;
  40426. }
  40427. TorusGeometry.prototype._regenerateVertexData = function () {
  40428. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40429. };
  40430. TorusGeometry.prototype.copy = function (id) {
  40431. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40432. };
  40433. TorusGeometry.prototype.serialize = function () {
  40434. var serializationObject = _super.prototype.serialize.call(this);
  40435. serializationObject.diameter = this.diameter;
  40436. serializationObject.thickness = this.thickness;
  40437. serializationObject.tessellation = this.tessellation;
  40438. return serializationObject;
  40439. };
  40440. TorusGeometry.Parse = function (parsedTorus, scene) {
  40441. if (scene.getGeometryByID(parsedTorus.id)) {
  40442. return null; // null since geometry could be something else than a torus...
  40443. }
  40444. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40445. if (BABYLON.Tags) {
  40446. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40447. }
  40448. scene.pushGeometry(torus, true);
  40449. return torus;
  40450. };
  40451. return TorusGeometry;
  40452. }(_PrimitiveGeometry));
  40453. BABYLON.TorusGeometry = TorusGeometry;
  40454. /**
  40455. * Creates a new ground geometry
  40456. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40457. */
  40458. var GroundGeometry = /** @class */ (function (_super) {
  40459. __extends(GroundGeometry, _super);
  40460. /**
  40461. * Creates a new ground geometry
  40462. * @param id defines the unique ID of the geometry
  40463. * @param scene defines the hosting scene
  40464. * @param width defines the width of the ground
  40465. * @param height defines the height of the ground
  40466. * @param subdivisions defines the subdivisions to apply to the ground
  40467. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40468. * @param mesh defines the hosting mesh (can be null)
  40469. */
  40470. function GroundGeometry(id, scene,
  40471. /**
  40472. * Defines the width of the ground
  40473. */
  40474. width,
  40475. /**
  40476. * Defines the height of the ground
  40477. */
  40478. height,
  40479. /**
  40480. * Defines the subdivisions to apply to the ground
  40481. */
  40482. subdivisions, canBeRegenerated, mesh) {
  40483. if (mesh === void 0) { mesh = null; }
  40484. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40485. _this.width = width;
  40486. _this.height = height;
  40487. _this.subdivisions = subdivisions;
  40488. return _this;
  40489. }
  40490. GroundGeometry.prototype._regenerateVertexData = function () {
  40491. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40492. };
  40493. GroundGeometry.prototype.copy = function (id) {
  40494. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40495. };
  40496. GroundGeometry.prototype.serialize = function () {
  40497. var serializationObject = _super.prototype.serialize.call(this);
  40498. serializationObject.width = this.width;
  40499. serializationObject.height = this.height;
  40500. serializationObject.subdivisions = this.subdivisions;
  40501. return serializationObject;
  40502. };
  40503. GroundGeometry.Parse = function (parsedGround, scene) {
  40504. if (scene.getGeometryByID(parsedGround.id)) {
  40505. return null; // null since geometry could be something else than a ground...
  40506. }
  40507. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40508. if (BABYLON.Tags) {
  40509. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40510. }
  40511. scene.pushGeometry(ground, true);
  40512. return ground;
  40513. };
  40514. return GroundGeometry;
  40515. }(_PrimitiveGeometry));
  40516. BABYLON.GroundGeometry = GroundGeometry;
  40517. /**
  40518. * Creates a tiled ground geometry
  40519. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40520. */
  40521. var TiledGroundGeometry = /** @class */ (function (_super) {
  40522. __extends(TiledGroundGeometry, _super);
  40523. /**
  40524. * Creates a tiled ground geometry
  40525. * @param id defines the unique ID of the geometry
  40526. * @param scene defines the hosting scene
  40527. * @param xmin defines the minimum value on X axis
  40528. * @param zmin defines the minimum value on Z axis
  40529. * @param xmax defines the maximum value on X axis
  40530. * @param zmax defines the maximum value on Z axis
  40531. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40532. * @param precision defines the precision to use when computing the tiles
  40533. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40534. * @param mesh defines the hosting mesh (can be null)
  40535. */
  40536. function TiledGroundGeometry(id, scene,
  40537. /**
  40538. * Defines the minimum value on X axis
  40539. */
  40540. xmin,
  40541. /**
  40542. * Defines the minimum value on Z axis
  40543. */
  40544. zmin,
  40545. /**
  40546. * Defines the maximum value on X axis
  40547. */
  40548. xmax,
  40549. /**
  40550. * Defines the maximum value on Z axis
  40551. */
  40552. zmax,
  40553. /**
  40554. * Defines the subdivisions to apply to the ground
  40555. */
  40556. subdivisions,
  40557. /**
  40558. * Defines the precision to use when computing the tiles
  40559. */
  40560. precision, canBeRegenerated, mesh) {
  40561. if (mesh === void 0) { mesh = null; }
  40562. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40563. _this.xmin = xmin;
  40564. _this.zmin = zmin;
  40565. _this.xmax = xmax;
  40566. _this.zmax = zmax;
  40567. _this.subdivisions = subdivisions;
  40568. _this.precision = precision;
  40569. return _this;
  40570. }
  40571. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40572. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40573. };
  40574. TiledGroundGeometry.prototype.copy = function (id) {
  40575. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40576. };
  40577. return TiledGroundGeometry;
  40578. }(_PrimitiveGeometry));
  40579. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40580. /**
  40581. * Creates a plane geometry
  40582. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40583. */
  40584. var PlaneGeometry = /** @class */ (function (_super) {
  40585. __extends(PlaneGeometry, _super);
  40586. /**
  40587. * Creates a plane geometry
  40588. * @param id defines the unique ID of the geometry
  40589. * @param scene defines the hosting scene
  40590. * @param size defines the size of the plane (width === height)
  40591. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40592. * @param mesh defines the hosting mesh (can be null)
  40593. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40594. */
  40595. function PlaneGeometry(id, scene,
  40596. /**
  40597. * Defines the size of the plane (width === height)
  40598. */
  40599. size, canBeRegenerated, mesh,
  40600. /**
  40601. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40602. */
  40603. side) {
  40604. if (mesh === void 0) { mesh = null; }
  40605. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40606. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40607. _this.size = size;
  40608. _this.side = side;
  40609. return _this;
  40610. }
  40611. PlaneGeometry.prototype._regenerateVertexData = function () {
  40612. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40613. };
  40614. PlaneGeometry.prototype.copy = function (id) {
  40615. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40616. };
  40617. PlaneGeometry.prototype.serialize = function () {
  40618. var serializationObject = _super.prototype.serialize.call(this);
  40619. serializationObject.size = this.size;
  40620. return serializationObject;
  40621. };
  40622. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40623. if (scene.getGeometryByID(parsedPlane.id)) {
  40624. return null; // null since geometry could be something else than a ground...
  40625. }
  40626. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40627. if (BABYLON.Tags) {
  40628. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40629. }
  40630. scene.pushGeometry(plane, true);
  40631. return plane;
  40632. };
  40633. return PlaneGeometry;
  40634. }(_PrimitiveGeometry));
  40635. BABYLON.PlaneGeometry = PlaneGeometry;
  40636. /**
  40637. * Creates a torus knot geometry
  40638. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40639. */
  40640. var TorusKnotGeometry = /** @class */ (function (_super) {
  40641. __extends(TorusKnotGeometry, _super);
  40642. /**
  40643. * Creates a torus knot geometry
  40644. * @param id defines the unique ID of the geometry
  40645. * @param scene defines the hosting scene
  40646. * @param radius defines the radius of the torus knot
  40647. * @param tube defines the thickness of the torus knot tube
  40648. * @param radialSegments defines the number of radial segments
  40649. * @param tubularSegments defines the number of tubular segments
  40650. * @param p defines the first number of windings
  40651. * @param q defines the second number of windings
  40652. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40653. * @param mesh defines the hosting mesh (can be null)
  40654. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40655. */
  40656. function TorusKnotGeometry(id, scene,
  40657. /**
  40658. * Defines the radius of the torus knot
  40659. */
  40660. radius,
  40661. /**
  40662. * Defines the thickness of the torus knot tube
  40663. */
  40664. tube,
  40665. /**
  40666. * Defines the number of radial segments
  40667. */
  40668. radialSegments,
  40669. /**
  40670. * Defines the number of tubular segments
  40671. */
  40672. tubularSegments,
  40673. /**
  40674. * Defines the first number of windings
  40675. */
  40676. p,
  40677. /**
  40678. * Defines the second number of windings
  40679. */
  40680. q, canBeRegenerated, mesh,
  40681. /**
  40682. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40683. */
  40684. side) {
  40685. if (mesh === void 0) { mesh = null; }
  40686. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40687. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40688. _this.radius = radius;
  40689. _this.tube = tube;
  40690. _this.radialSegments = radialSegments;
  40691. _this.tubularSegments = tubularSegments;
  40692. _this.p = p;
  40693. _this.q = q;
  40694. _this.side = side;
  40695. return _this;
  40696. }
  40697. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40698. 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 });
  40699. };
  40700. TorusKnotGeometry.prototype.copy = function (id) {
  40701. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40702. };
  40703. TorusKnotGeometry.prototype.serialize = function () {
  40704. var serializationObject = _super.prototype.serialize.call(this);
  40705. serializationObject.radius = this.radius;
  40706. serializationObject.tube = this.tube;
  40707. serializationObject.radialSegments = this.radialSegments;
  40708. serializationObject.tubularSegments = this.tubularSegments;
  40709. serializationObject.p = this.p;
  40710. serializationObject.q = this.q;
  40711. return serializationObject;
  40712. };
  40713. ;
  40714. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40715. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40716. return null; // null since geometry could be something else than a ground...
  40717. }
  40718. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40719. if (BABYLON.Tags) {
  40720. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40721. }
  40722. scene.pushGeometry(torusKnot, true);
  40723. return torusKnot;
  40724. };
  40725. return TorusKnotGeometry;
  40726. }(_PrimitiveGeometry));
  40727. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40728. //}
  40729. })(BABYLON || (BABYLON = {}));
  40730. //# sourceMappingURL=babylon.geometry.js.map
  40731. var BABYLON;
  40732. (function (BABYLON) {
  40733. /**
  40734. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40735. */
  40736. var PerformanceMonitor = /** @class */ (function () {
  40737. /**
  40738. * constructor
  40739. * @param frameSampleSize The number of samples required to saturate the sliding window
  40740. */
  40741. function PerformanceMonitor(frameSampleSize) {
  40742. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40743. this._enabled = true;
  40744. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40745. }
  40746. /**
  40747. * Samples current frame
  40748. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40749. */
  40750. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40751. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40752. if (!this._enabled)
  40753. return;
  40754. if (this._lastFrameTimeMs != null) {
  40755. var dt = timeMs - this._lastFrameTimeMs;
  40756. this._rollingFrameTime.add(dt);
  40757. }
  40758. this._lastFrameTimeMs = timeMs;
  40759. };
  40760. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40761. /**
  40762. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40763. * @return Average frame time in milliseconds
  40764. */
  40765. get: function () {
  40766. return this._rollingFrameTime.average;
  40767. },
  40768. enumerable: true,
  40769. configurable: true
  40770. });
  40771. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40772. /**
  40773. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40774. * @return Frame time variance in milliseconds squared
  40775. */
  40776. get: function () {
  40777. return this._rollingFrameTime.variance;
  40778. },
  40779. enumerable: true,
  40780. configurable: true
  40781. });
  40782. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40783. /**
  40784. * Returns the frame time of the most recent frame
  40785. * @return Frame time in milliseconds
  40786. */
  40787. get: function () {
  40788. return this._rollingFrameTime.history(0);
  40789. },
  40790. enumerable: true,
  40791. configurable: true
  40792. });
  40793. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40794. /**
  40795. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40796. * @return Framerate in frames per second
  40797. */
  40798. get: function () {
  40799. return 1000.0 / this._rollingFrameTime.average;
  40800. },
  40801. enumerable: true,
  40802. configurable: true
  40803. });
  40804. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40805. /**
  40806. * Returns the average framerate in frames per second using the most recent frame time
  40807. * @return Framerate in frames per second
  40808. */
  40809. get: function () {
  40810. var history = this._rollingFrameTime.history(0);
  40811. if (history === 0) {
  40812. return 0;
  40813. }
  40814. return 1000.0 / history;
  40815. },
  40816. enumerable: true,
  40817. configurable: true
  40818. });
  40819. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40820. /**
  40821. * Returns true if enough samples have been taken to completely fill the sliding window
  40822. * @return true if saturated
  40823. */
  40824. get: function () {
  40825. return this._rollingFrameTime.isSaturated();
  40826. },
  40827. enumerable: true,
  40828. configurable: true
  40829. });
  40830. /**
  40831. * Enables contributions to the sliding window sample set
  40832. */
  40833. PerformanceMonitor.prototype.enable = function () {
  40834. this._enabled = true;
  40835. };
  40836. /**
  40837. * Disables contributions to the sliding window sample set
  40838. * Samples will not be interpolated over the disabled period
  40839. */
  40840. PerformanceMonitor.prototype.disable = function () {
  40841. this._enabled = false;
  40842. //clear last sample to avoid interpolating over the disabled period when next enabled
  40843. this._lastFrameTimeMs = null;
  40844. };
  40845. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40846. /**
  40847. * Returns true if sampling is enabled
  40848. * @return true if enabled
  40849. */
  40850. get: function () {
  40851. return this._enabled;
  40852. },
  40853. enumerable: true,
  40854. configurable: true
  40855. });
  40856. /**
  40857. * Resets performance monitor
  40858. */
  40859. PerformanceMonitor.prototype.reset = function () {
  40860. //clear last sample to avoid interpolating over the disabled period when next enabled
  40861. this._lastFrameTimeMs = null;
  40862. //wipe record
  40863. this._rollingFrameTime.reset();
  40864. };
  40865. return PerformanceMonitor;
  40866. }());
  40867. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40868. /**
  40869. * RollingAverage
  40870. *
  40871. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40872. */
  40873. var RollingAverage = /** @class */ (function () {
  40874. /**
  40875. * constructor
  40876. * @param length The number of samples required to saturate the sliding window
  40877. */
  40878. function RollingAverage(length) {
  40879. this._samples = new Array(length);
  40880. this.reset();
  40881. }
  40882. /**
  40883. * Adds a sample to the sample set
  40884. * @param v The sample value
  40885. */
  40886. RollingAverage.prototype.add = function (v) {
  40887. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40888. var delta;
  40889. //we need to check if we've already wrapped round
  40890. if (this.isSaturated()) {
  40891. //remove bottom of stack from mean
  40892. var bottomValue = this._samples[this._pos];
  40893. delta = bottomValue - this.average;
  40894. this.average -= delta / (this._sampleCount - 1);
  40895. this._m2 -= delta * (bottomValue - this.average);
  40896. }
  40897. else {
  40898. this._sampleCount++;
  40899. }
  40900. //add new value to mean
  40901. delta = v - this.average;
  40902. this.average += delta / (this._sampleCount);
  40903. this._m2 += delta * (v - this.average);
  40904. //set the new variance
  40905. this.variance = this._m2 / (this._sampleCount - 1);
  40906. this._samples[this._pos] = v;
  40907. this._pos++;
  40908. this._pos %= this._samples.length; //positive wrap around
  40909. };
  40910. /**
  40911. * Returns previously added values or null if outside of history or outside the sliding window domain
  40912. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40913. * @return Value previously recorded with add() or null if outside of range
  40914. */
  40915. RollingAverage.prototype.history = function (i) {
  40916. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40917. return 0;
  40918. }
  40919. var i0 = this._wrapPosition(this._pos - 1.0);
  40920. return this._samples[this._wrapPosition(i0 - i)];
  40921. };
  40922. /**
  40923. * Returns true if enough samples have been taken to completely fill the sliding window
  40924. * @return true if sample-set saturated
  40925. */
  40926. RollingAverage.prototype.isSaturated = function () {
  40927. return this._sampleCount >= this._samples.length;
  40928. };
  40929. /**
  40930. * Resets the rolling average (equivalent to 0 samples taken so far)
  40931. */
  40932. RollingAverage.prototype.reset = function () {
  40933. this.average = 0;
  40934. this.variance = 0;
  40935. this._sampleCount = 0;
  40936. this._pos = 0;
  40937. this._m2 = 0;
  40938. };
  40939. /**
  40940. * Wraps a value around the sample range boundaries
  40941. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40942. * @return Wrapped position in sample range
  40943. */
  40944. RollingAverage.prototype._wrapPosition = function (i) {
  40945. var max = this._samples.length;
  40946. return ((i % max) + max) % max;
  40947. };
  40948. return RollingAverage;
  40949. }());
  40950. BABYLON.RollingAverage = RollingAverage;
  40951. })(BABYLON || (BABYLON = {}));
  40952. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40953. var BABYLON;
  40954. (function (BABYLON) {
  40955. /**
  40956. * "Static Class" containing the most commonly used helper while dealing with material for
  40957. * rendering purpose.
  40958. *
  40959. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40960. *
  40961. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40962. */
  40963. var MaterialHelper = /** @class */ (function () {
  40964. function MaterialHelper() {
  40965. }
  40966. /**
  40967. * Bind the current view position to an effect.
  40968. * @param effect The effect to be bound
  40969. * @param scene The scene the eyes position is used from
  40970. */
  40971. MaterialHelper.BindEyePosition = function (effect, scene) {
  40972. if (scene._forcedViewPosition) {
  40973. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40974. return;
  40975. }
  40976. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40977. };
  40978. /**
  40979. * Helps preparing the defines values about the UVs in used in the effect.
  40980. * UVs are shared as much as we can accross chanels in the shaders.
  40981. * @param texture The texture we are preparing the UVs for
  40982. * @param defines The defines to update
  40983. * @param key The chanel key "diffuse", "specular"... used in the shader
  40984. */
  40985. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40986. defines._needUVs = true;
  40987. defines[key] = true;
  40988. if (texture.getTextureMatrix().isIdentity(true)) {
  40989. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40990. if (texture.coordinatesIndex === 0) {
  40991. defines["MAINUV1"] = true;
  40992. }
  40993. else {
  40994. defines["MAINUV2"] = true;
  40995. }
  40996. }
  40997. else {
  40998. defines[key + "DIRECTUV"] = 0;
  40999. }
  41000. };
  41001. /**
  41002. * Binds a texture matrix value to its corrsponding uniform
  41003. * @param texture The texture to bind the matrix for
  41004. * @param uniformBuffer The uniform buffer receivin the data
  41005. * @param key The chanel key "diffuse", "specular"... used in the shader
  41006. */
  41007. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41008. var matrix = texture.getTextureMatrix();
  41009. if (!matrix.isIdentity(true)) {
  41010. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41011. }
  41012. };
  41013. /**
  41014. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41015. * @param mesh defines the current mesh
  41016. * @param scene defines the current scene
  41017. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41018. * @param pointsCloud defines if point cloud rendering has to be turned on
  41019. * @param fogEnabled defines if fog has to be turned on
  41020. * @param alphaTest defines if alpha testing has to be turned on
  41021. * @param defines defines the current list of defines
  41022. */
  41023. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41024. if (defines._areMiscDirty) {
  41025. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41026. defines["POINTSIZE"] = pointsCloud;
  41027. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41028. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41029. defines["ALPHATEST"] = alphaTest;
  41030. }
  41031. };
  41032. /**
  41033. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41034. * @param scene defines the current scene
  41035. * @param engine defines the current engine
  41036. * @param defines specifies the list of active defines
  41037. * @param useInstances defines if instances have to be turned on
  41038. * @param useClipPlane defines if clip plane have to be turned on
  41039. */
  41040. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41041. if (useClipPlane === void 0) { useClipPlane = null; }
  41042. var changed = false;
  41043. if (useClipPlane == null) {
  41044. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41045. }
  41046. if (defines["CLIPPLANE"] !== useClipPlane) {
  41047. defines["CLIPPLANE"] = useClipPlane;
  41048. changed = true;
  41049. }
  41050. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41051. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41052. changed = true;
  41053. }
  41054. if (defines["INSTANCES"] !== useInstances) {
  41055. defines["INSTANCES"] = useInstances;
  41056. changed = true;
  41057. }
  41058. if (changed) {
  41059. defines.markAsUnprocessed();
  41060. }
  41061. };
  41062. /**
  41063. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41064. * @param mesh The mesh containing the geometry data we will draw
  41065. * @param defines The defines to update
  41066. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41067. * @param useBones Precise whether bones should be used or not (override mesh info)
  41068. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41069. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41070. * @returns false if defines are considered not dirty and have not been checked
  41071. */
  41072. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41073. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41074. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41075. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41076. return false;
  41077. }
  41078. defines._normals = defines._needNormals;
  41079. defines._uvs = defines._needUVs;
  41080. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41081. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41082. defines["TANGENT"] = true;
  41083. }
  41084. if (defines._needUVs) {
  41085. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41086. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41087. }
  41088. else {
  41089. defines["UV1"] = false;
  41090. defines["UV2"] = false;
  41091. }
  41092. if (useVertexColor) {
  41093. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41094. defines["VERTEXCOLOR"] = hasVertexColors;
  41095. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41096. }
  41097. if (useBones) {
  41098. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41099. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41100. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41101. }
  41102. else {
  41103. defines["NUM_BONE_INFLUENCERS"] = 0;
  41104. defines["BonesPerMesh"] = 0;
  41105. }
  41106. }
  41107. if (useMorphTargets) {
  41108. var manager = mesh.morphTargetManager;
  41109. if (manager) {
  41110. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41111. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41112. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41113. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41114. }
  41115. else {
  41116. defines["MORPHTARGETS_TANGENT"] = false;
  41117. defines["MORPHTARGETS_NORMAL"] = false;
  41118. defines["MORPHTARGETS"] = false;
  41119. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41120. }
  41121. }
  41122. return true;
  41123. };
  41124. /**
  41125. * Prepares the defines related to the light information passed in parameter
  41126. * @param scene The scene we are intending to draw
  41127. * @param mesh The mesh the effect is compiling for
  41128. * @param defines The defines to update
  41129. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41130. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41131. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41132. * @returns true if normals will be required for the rest of the effect
  41133. */
  41134. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41135. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41136. if (disableLighting === void 0) { disableLighting = false; }
  41137. if (!defines._areLightsDirty) {
  41138. return defines._needNormals;
  41139. }
  41140. var lightIndex = 0;
  41141. var needNormals = false;
  41142. var needRebuild = false;
  41143. var lightmapMode = false;
  41144. var shadowEnabled = false;
  41145. var specularEnabled = false;
  41146. if (scene.lightsEnabled && !disableLighting) {
  41147. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41148. var light = _a[_i];
  41149. needNormals = true;
  41150. if (defines["LIGHT" + lightIndex] === undefined) {
  41151. needRebuild = true;
  41152. }
  41153. defines["LIGHT" + lightIndex] = true;
  41154. defines["SPOTLIGHT" + lightIndex] = false;
  41155. defines["HEMILIGHT" + lightIndex] = false;
  41156. defines["POINTLIGHT" + lightIndex] = false;
  41157. defines["DIRLIGHT" + lightIndex] = false;
  41158. var type;
  41159. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41160. type = "SPOTLIGHT" + lightIndex;
  41161. var spotLight = light;
  41162. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41163. }
  41164. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41165. type = "HEMILIGHT" + lightIndex;
  41166. }
  41167. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41168. type = "POINTLIGHT" + lightIndex;
  41169. }
  41170. else {
  41171. type = "DIRLIGHT" + lightIndex;
  41172. }
  41173. defines[type] = true;
  41174. // Specular
  41175. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41176. specularEnabled = true;
  41177. }
  41178. // Shadows
  41179. defines["SHADOW" + lightIndex] = false;
  41180. defines["SHADOWPCF" + lightIndex] = false;
  41181. defines["SHADOWPCSS" + lightIndex] = false;
  41182. defines["SHADOWPOISSON" + lightIndex] = false;
  41183. defines["SHADOWESM" + lightIndex] = false;
  41184. defines["SHADOWCUBE" + lightIndex] = false;
  41185. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41186. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41187. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41188. var shadowGenerator = light.getShadowGenerator();
  41189. if (shadowGenerator) {
  41190. shadowEnabled = true;
  41191. shadowGenerator.prepareDefines(defines, lightIndex);
  41192. }
  41193. }
  41194. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41195. lightmapMode = true;
  41196. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41197. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41198. }
  41199. else {
  41200. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41201. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41202. }
  41203. lightIndex++;
  41204. if (lightIndex === maxSimultaneousLights)
  41205. break;
  41206. }
  41207. }
  41208. defines["SPECULARTERM"] = specularEnabled;
  41209. defines["SHADOWS"] = shadowEnabled;
  41210. // Resetting all other lights if any
  41211. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41212. if (defines["LIGHT" + index] !== undefined) {
  41213. defines["LIGHT" + index] = false;
  41214. defines["HEMILIGHT" + lightIndex] = false;
  41215. defines["POINTLIGHT" + lightIndex] = false;
  41216. defines["DIRLIGHT" + lightIndex] = false;
  41217. defines["SPOTLIGHT" + lightIndex] = false;
  41218. defines["SHADOW" + lightIndex] = false;
  41219. }
  41220. }
  41221. var caps = scene.getEngine().getCaps();
  41222. if (defines["SHADOWFLOAT"] === undefined) {
  41223. needRebuild = true;
  41224. }
  41225. defines["SHADOWFLOAT"] = shadowEnabled &&
  41226. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41227. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41228. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41229. if (needRebuild) {
  41230. defines.rebuild();
  41231. }
  41232. return needNormals;
  41233. };
  41234. /**
  41235. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41236. * that won t be acctive due to defines being turned off.
  41237. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41238. * @param samplersList The samplers list
  41239. * @param defines The defines helping in the list generation
  41240. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41241. */
  41242. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41243. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41244. var uniformsList;
  41245. var uniformBuffersList = null;
  41246. if (uniformsListOrOptions.uniformsNames) {
  41247. var options = uniformsListOrOptions;
  41248. uniformsList = options.uniformsNames;
  41249. uniformBuffersList = options.uniformBuffersNames;
  41250. samplersList = options.samplers;
  41251. defines = options.defines;
  41252. maxSimultaneousLights = options.maxSimultaneousLights;
  41253. }
  41254. else {
  41255. uniformsList = uniformsListOrOptions;
  41256. if (!samplersList) {
  41257. samplersList = [];
  41258. }
  41259. }
  41260. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41261. if (!defines["LIGHT" + lightIndex]) {
  41262. break;
  41263. }
  41264. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41265. if (uniformBuffersList) {
  41266. uniformBuffersList.push("Light" + lightIndex);
  41267. }
  41268. samplersList.push("shadowSampler" + lightIndex);
  41269. samplersList.push("depthSampler" + lightIndex);
  41270. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41271. samplersList.push("projectionLightSampler" + lightIndex);
  41272. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41273. }
  41274. }
  41275. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41276. uniformsList.push("morphTargetInfluences");
  41277. }
  41278. };
  41279. /**
  41280. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41281. * @param defines The defines to update while falling back
  41282. * @param fallbacks The authorized effect fallbacks
  41283. * @param maxSimultaneousLights The maximum number of lights allowed
  41284. * @param rank the current rank of the Effect
  41285. * @returns The newly affected rank
  41286. */
  41287. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41288. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41289. if (rank === void 0) { rank = 0; }
  41290. var lightFallbackRank = 0;
  41291. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41292. if (!defines["LIGHT" + lightIndex]) {
  41293. break;
  41294. }
  41295. if (lightIndex > 0) {
  41296. lightFallbackRank = rank + lightIndex;
  41297. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41298. }
  41299. if (!defines["SHADOWS"]) {
  41300. if (defines["SHADOW" + lightIndex]) {
  41301. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41302. }
  41303. if (defines["SHADOWPCF" + lightIndex]) {
  41304. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41305. }
  41306. if (defines["SHADOWPCSS" + lightIndex]) {
  41307. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41308. }
  41309. if (defines["SHADOWPOISSON" + lightIndex]) {
  41310. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41311. }
  41312. if (defines["SHADOWESM" + lightIndex]) {
  41313. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41314. }
  41315. }
  41316. }
  41317. return lightFallbackRank++;
  41318. };
  41319. /**
  41320. * Prepares the list of attributes required for morph targets according to the effect defines.
  41321. * @param attribs The current list of supported attribs
  41322. * @param mesh The mesh to prepare the morph targets attributes for
  41323. * @param defines The current Defines of the effect
  41324. */
  41325. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41326. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41327. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41328. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41329. var manager = mesh.morphTargetManager;
  41330. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41331. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41332. for (var index = 0; index < influencers; index++) {
  41333. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41334. if (normal) {
  41335. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41336. }
  41337. if (tangent) {
  41338. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41339. }
  41340. if (attribs.length > maxAttributesCount) {
  41341. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41342. }
  41343. }
  41344. }
  41345. };
  41346. /**
  41347. * Prepares the list of attributes required for bones according to the effect defines.
  41348. * @param attribs The current list of supported attribs
  41349. * @param mesh The mesh to prepare the bones attributes for
  41350. * @param defines The current Defines of the effect
  41351. * @param fallbacks The current efffect fallback strategy
  41352. */
  41353. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41354. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41355. fallbacks.addCPUSkinningFallback(0, mesh);
  41356. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41357. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41358. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41359. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41360. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41361. }
  41362. }
  41363. };
  41364. /**
  41365. * Prepares the list of attributes required for instances according to the effect defines.
  41366. * @param attribs The current list of supported attribs
  41367. * @param defines The current Defines of the effect
  41368. */
  41369. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41370. if (defines["INSTANCES"]) {
  41371. attribs.push("world0");
  41372. attribs.push("world1");
  41373. attribs.push("world2");
  41374. attribs.push("world3");
  41375. }
  41376. };
  41377. /**
  41378. * Binds the light shadow information to the effect for the given mesh.
  41379. * @param light The light containing the generator
  41380. * @param scene The scene the lights belongs to
  41381. * @param mesh The mesh we are binding the information to render
  41382. * @param lightIndex The light index in the effect used to render the mesh
  41383. * @param effect The effect we are binding the data to
  41384. */
  41385. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41386. if (light.shadowEnabled && mesh.receiveShadows) {
  41387. var shadowGenerator = light.getShadowGenerator();
  41388. if (shadowGenerator) {
  41389. shadowGenerator.bindShadowLight(lightIndex, effect);
  41390. }
  41391. }
  41392. };
  41393. /**
  41394. * Binds the light information to the effect.
  41395. * @param light The light containing the generator
  41396. * @param effect The effect we are binding the data to
  41397. * @param lightIndex The light index in the effect used to render
  41398. */
  41399. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41400. light.transferToEffect(effect, lightIndex + "");
  41401. };
  41402. /**
  41403. * Binds the lights information from the scene to the effect for the given mesh.
  41404. * @param scene The scene the lights belongs to
  41405. * @param mesh The mesh we are binding the information to render
  41406. * @param effect The effect we are binding the data to
  41407. * @param defines The generated defines for the effect
  41408. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41409. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41410. */
  41411. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41412. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41413. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41414. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41415. for (var i = 0; i < len; i++) {
  41416. var light = mesh._lightSources[i];
  41417. var iAsString = i.toString();
  41418. var scaledIntensity = light.getScaledIntensity();
  41419. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41420. MaterialHelper.BindLightProperties(light, effect, i);
  41421. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41422. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41423. if (defines["SPECULARTERM"]) {
  41424. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41425. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41426. }
  41427. // Shadows
  41428. if (scene.shadowsEnabled) {
  41429. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41430. }
  41431. light._uniformBuffer.update();
  41432. }
  41433. };
  41434. /**
  41435. * Binds the fog information from the scene to the effect for the given mesh.
  41436. * @param scene The scene the lights belongs to
  41437. * @param mesh The mesh we are binding the information to render
  41438. * @param effect The effect we are binding the data to
  41439. */
  41440. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41441. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41442. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41443. effect.setColor3("vFogColor", scene.fogColor);
  41444. }
  41445. };
  41446. /**
  41447. * Binds the bones information from the mesh to the effect.
  41448. * @param mesh The mesh we are binding the information to render
  41449. * @param effect The effect we are binding the data to
  41450. */
  41451. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41452. if (!effect || !mesh) {
  41453. return;
  41454. }
  41455. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41456. mesh.computeBonesUsingShaders = false;
  41457. }
  41458. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41459. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41460. if (matrices) {
  41461. effect.setMatrices("mBones", matrices);
  41462. }
  41463. }
  41464. };
  41465. /**
  41466. * Binds the morph targets information from the mesh to the effect.
  41467. * @param abstractMesh The mesh we are binding the information to render
  41468. * @param effect The effect we are binding the data to
  41469. */
  41470. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41471. var manager = abstractMesh.morphTargetManager;
  41472. if (!abstractMesh || !manager) {
  41473. return;
  41474. }
  41475. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41476. };
  41477. /**
  41478. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41479. * @param defines The generated defines used in the effect
  41480. * @param effect The effect we are binding the data to
  41481. * @param scene The scene we are willing to render with logarithmic scale for
  41482. */
  41483. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41484. if (defines["LOGARITHMICDEPTH"]) {
  41485. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41486. }
  41487. };
  41488. /**
  41489. * Binds the clip plane information from the scene to the effect.
  41490. * @param scene The scene the clip plane information are extracted from
  41491. * @param effect The effect we are binding the data to
  41492. */
  41493. MaterialHelper.BindClipPlane = function (effect, scene) {
  41494. if (scene.clipPlane) {
  41495. var clipPlane = scene.clipPlane;
  41496. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41497. }
  41498. };
  41499. return MaterialHelper;
  41500. }());
  41501. BABYLON.MaterialHelper = MaterialHelper;
  41502. })(BABYLON || (BABYLON = {}));
  41503. //# sourceMappingURL=babylon.materialHelper.js.map
  41504. var BABYLON;
  41505. (function (BABYLON) {
  41506. var PushMaterial = /** @class */ (function (_super) {
  41507. __extends(PushMaterial, _super);
  41508. function PushMaterial(name, scene) {
  41509. var _this = _super.call(this, name, scene) || this;
  41510. _this._normalMatrix = new BABYLON.Matrix();
  41511. _this.storeEffectOnSubMeshes = true;
  41512. return _this;
  41513. }
  41514. PushMaterial.prototype.getEffect = function () {
  41515. return this._activeEffect;
  41516. };
  41517. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41518. if (!mesh) {
  41519. return false;
  41520. }
  41521. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41522. return true;
  41523. }
  41524. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41525. };
  41526. /**
  41527. * Binds the given world matrix to the active effect
  41528. *
  41529. * @param world the matrix to bind
  41530. */
  41531. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41532. this._activeEffect.setMatrix("world", world);
  41533. };
  41534. /**
  41535. * Binds the given normal matrix to the active effect
  41536. *
  41537. * @param normalMatrix the matrix to bind
  41538. */
  41539. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41540. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41541. };
  41542. PushMaterial.prototype.bind = function (world, mesh) {
  41543. if (!mesh) {
  41544. return;
  41545. }
  41546. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41547. };
  41548. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41549. if (effect === void 0) { effect = null; }
  41550. _super.prototype._afterBind.call(this, mesh);
  41551. this.getScene()._cachedEffect = effect;
  41552. };
  41553. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41554. if (visibility === void 0) { visibility = 1; }
  41555. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41556. };
  41557. return PushMaterial;
  41558. }(BABYLON.Material));
  41559. BABYLON.PushMaterial = PushMaterial;
  41560. })(BABYLON || (BABYLON = {}));
  41561. //# sourceMappingURL=babylon.pushMaterial.js.map
  41562. var BABYLON;
  41563. (function (BABYLON) {
  41564. /** @hidden */
  41565. var StandardMaterialDefines = /** @class */ (function (_super) {
  41566. __extends(StandardMaterialDefines, _super);
  41567. function StandardMaterialDefines() {
  41568. var _this = _super.call(this) || this;
  41569. _this.MAINUV1 = false;
  41570. _this.MAINUV2 = false;
  41571. _this.DIFFUSE = false;
  41572. _this.DIFFUSEDIRECTUV = 0;
  41573. _this.AMBIENT = false;
  41574. _this.AMBIENTDIRECTUV = 0;
  41575. _this.OPACITY = false;
  41576. _this.OPACITYDIRECTUV = 0;
  41577. _this.OPACITYRGB = false;
  41578. _this.REFLECTION = false;
  41579. _this.EMISSIVE = false;
  41580. _this.EMISSIVEDIRECTUV = 0;
  41581. _this.SPECULAR = false;
  41582. _this.SPECULARDIRECTUV = 0;
  41583. _this.BUMP = false;
  41584. _this.BUMPDIRECTUV = 0;
  41585. _this.PARALLAX = false;
  41586. _this.PARALLAXOCCLUSION = false;
  41587. _this.SPECULAROVERALPHA = false;
  41588. _this.CLIPPLANE = false;
  41589. _this.ALPHATEST = false;
  41590. _this.DEPTHPREPASS = false;
  41591. _this.ALPHAFROMDIFFUSE = false;
  41592. _this.POINTSIZE = false;
  41593. _this.FOG = false;
  41594. _this.SPECULARTERM = false;
  41595. _this.DIFFUSEFRESNEL = false;
  41596. _this.OPACITYFRESNEL = false;
  41597. _this.REFLECTIONFRESNEL = false;
  41598. _this.REFRACTIONFRESNEL = false;
  41599. _this.EMISSIVEFRESNEL = false;
  41600. _this.FRESNEL = false;
  41601. _this.NORMAL = false;
  41602. _this.UV1 = false;
  41603. _this.UV2 = false;
  41604. _this.VERTEXCOLOR = false;
  41605. _this.VERTEXALPHA = false;
  41606. _this.NUM_BONE_INFLUENCERS = 0;
  41607. _this.BonesPerMesh = 0;
  41608. _this.INSTANCES = false;
  41609. _this.GLOSSINESS = false;
  41610. _this.ROUGHNESS = false;
  41611. _this.EMISSIVEASILLUMINATION = false;
  41612. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41613. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41614. _this.LIGHTMAP = false;
  41615. _this.LIGHTMAPDIRECTUV = 0;
  41616. _this.OBJECTSPACE_NORMALMAP = false;
  41617. _this.USELIGHTMAPASSHADOWMAP = false;
  41618. _this.REFLECTIONMAP_3D = false;
  41619. _this.REFLECTIONMAP_SPHERICAL = false;
  41620. _this.REFLECTIONMAP_PLANAR = false;
  41621. _this.REFLECTIONMAP_CUBIC = false;
  41622. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41623. _this.REFLECTIONMAP_PROJECTION = false;
  41624. _this.REFLECTIONMAP_SKYBOX = false;
  41625. _this.REFLECTIONMAP_EXPLICIT = false;
  41626. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41627. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41628. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41629. _this.INVERTCUBICMAP = false;
  41630. _this.LOGARITHMICDEPTH = false;
  41631. _this.REFRACTION = false;
  41632. _this.REFRACTIONMAP_3D = false;
  41633. _this.REFLECTIONOVERALPHA = false;
  41634. _this.TWOSIDEDLIGHTING = false;
  41635. _this.SHADOWFLOAT = false;
  41636. _this.MORPHTARGETS = false;
  41637. _this.MORPHTARGETS_NORMAL = false;
  41638. _this.MORPHTARGETS_TANGENT = false;
  41639. _this.NUM_MORPH_INFLUENCERS = 0;
  41640. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41641. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41642. _this.IMAGEPROCESSING = false;
  41643. _this.VIGNETTE = false;
  41644. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41645. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41646. _this.TONEMAPPING = false;
  41647. _this.CONTRAST = false;
  41648. _this.COLORCURVES = false;
  41649. _this.COLORGRADING = false;
  41650. _this.COLORGRADING3D = false;
  41651. _this.SAMPLER3DGREENDEPTH = false;
  41652. _this.SAMPLER3DBGRMAP = false;
  41653. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41654. /**
  41655. * If the reflection texture on this material is in linear color space
  41656. * @hidden
  41657. */
  41658. _this.IS_REFLECTION_LINEAR = false;
  41659. /**
  41660. * If the refraction texture on this material is in linear color space
  41661. * @hidden
  41662. */
  41663. _this.IS_REFRACTION_LINEAR = false;
  41664. _this.EXPOSURE = false;
  41665. _this.rebuild();
  41666. return _this;
  41667. }
  41668. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41669. var modes = [
  41670. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41671. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41672. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41673. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41674. ];
  41675. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41676. var mode = modes_1[_i];
  41677. this[mode] = (mode === modeToEnable);
  41678. }
  41679. };
  41680. return StandardMaterialDefines;
  41681. }(BABYLON.MaterialDefines));
  41682. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41683. var StandardMaterial = /** @class */ (function (_super) {
  41684. __extends(StandardMaterial, _super);
  41685. function StandardMaterial(name, scene) {
  41686. var _this = _super.call(this, name, scene) || this;
  41687. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41688. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41689. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41690. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41691. _this.specularPower = 64;
  41692. _this._useAlphaFromDiffuseTexture = false;
  41693. _this._useEmissiveAsIllumination = false;
  41694. _this._linkEmissiveWithDiffuse = false;
  41695. _this._useSpecularOverAlpha = false;
  41696. _this._useReflectionOverAlpha = false;
  41697. _this._disableLighting = false;
  41698. _this._useObjectSpaceNormalMap = false;
  41699. _this._useParallax = false;
  41700. _this._useParallaxOcclusion = false;
  41701. _this.parallaxScaleBias = 0.05;
  41702. _this._roughness = 0;
  41703. _this.indexOfRefraction = 0.98;
  41704. _this.invertRefractionY = true;
  41705. /**
  41706. * Defines the alpha limits in alpha test mode
  41707. */
  41708. _this.alphaCutOff = 0.4;
  41709. _this._useLightmapAsShadowmap = false;
  41710. _this._useReflectionFresnelFromSpecular = false;
  41711. _this._useGlossinessFromSpecularMapAlpha = false;
  41712. _this._maxSimultaneousLights = 4;
  41713. /**
  41714. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41715. */
  41716. _this._invertNormalMapX = false;
  41717. /**
  41718. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41719. */
  41720. _this._invertNormalMapY = false;
  41721. /**
  41722. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41723. */
  41724. _this._twoSidedLighting = false;
  41725. _this._renderTargets = new BABYLON.SmartArray(16);
  41726. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41727. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41728. // Setup the default processing configuration to the scene.
  41729. _this._attachImageProcessingConfiguration(null);
  41730. _this.getRenderTargetTextures = function () {
  41731. _this._renderTargets.reset();
  41732. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41733. _this._renderTargets.push(_this._reflectionTexture);
  41734. }
  41735. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41736. _this._renderTargets.push(_this._refractionTexture);
  41737. }
  41738. return _this._renderTargets;
  41739. };
  41740. return _this;
  41741. }
  41742. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41743. /**
  41744. * Gets the image processing configuration used either in this material.
  41745. */
  41746. get: function () {
  41747. return this._imageProcessingConfiguration;
  41748. },
  41749. /**
  41750. * Sets the Default image processing configuration used either in the this material.
  41751. *
  41752. * If sets to null, the scene one is in use.
  41753. */
  41754. set: function (value) {
  41755. this._attachImageProcessingConfiguration(value);
  41756. // Ensure the effect will be rebuilt.
  41757. this._markAllSubMeshesAsTexturesDirty();
  41758. },
  41759. enumerable: true,
  41760. configurable: true
  41761. });
  41762. /**
  41763. * Attaches a new image processing configuration to the Standard Material.
  41764. * @param configuration
  41765. */
  41766. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41767. var _this = this;
  41768. if (configuration === this._imageProcessingConfiguration) {
  41769. return;
  41770. }
  41771. // Detaches observer.
  41772. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41773. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41774. }
  41775. // Pick the scene configuration if needed.
  41776. if (!configuration) {
  41777. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41778. }
  41779. else {
  41780. this._imageProcessingConfiguration = configuration;
  41781. }
  41782. // Attaches observer.
  41783. if (this._imageProcessingConfiguration) {
  41784. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41785. _this._markAllSubMeshesAsImageProcessingDirty();
  41786. });
  41787. }
  41788. };
  41789. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41790. /**
  41791. * Gets wether the color curves effect is enabled.
  41792. */
  41793. get: function () {
  41794. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41795. },
  41796. /**
  41797. * Sets wether the color curves effect is enabled.
  41798. */
  41799. set: function (value) {
  41800. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41801. },
  41802. enumerable: true,
  41803. configurable: true
  41804. });
  41805. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41806. /**
  41807. * Gets wether the color grading effect is enabled.
  41808. */
  41809. get: function () {
  41810. return this.imageProcessingConfiguration.colorGradingEnabled;
  41811. },
  41812. /**
  41813. * Gets wether the color grading effect is enabled.
  41814. */
  41815. set: function (value) {
  41816. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41817. },
  41818. enumerable: true,
  41819. configurable: true
  41820. });
  41821. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41822. /**
  41823. * Gets wether tonemapping is enabled or not.
  41824. */
  41825. get: function () {
  41826. return this._imageProcessingConfiguration.toneMappingEnabled;
  41827. },
  41828. /**
  41829. * Sets wether tonemapping is enabled or not
  41830. */
  41831. set: function (value) {
  41832. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41833. },
  41834. enumerable: true,
  41835. configurable: true
  41836. });
  41837. ;
  41838. ;
  41839. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41840. /**
  41841. * The camera exposure used on this material.
  41842. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41843. * This corresponds to a photographic exposure.
  41844. */
  41845. get: function () {
  41846. return this._imageProcessingConfiguration.exposure;
  41847. },
  41848. /**
  41849. * The camera exposure used on this material.
  41850. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41851. * This corresponds to a photographic exposure.
  41852. */
  41853. set: function (value) {
  41854. this._imageProcessingConfiguration.exposure = value;
  41855. },
  41856. enumerable: true,
  41857. configurable: true
  41858. });
  41859. ;
  41860. ;
  41861. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41862. /**
  41863. * Gets The camera contrast used on this material.
  41864. */
  41865. get: function () {
  41866. return this._imageProcessingConfiguration.contrast;
  41867. },
  41868. /**
  41869. * Sets The camera contrast used on this material.
  41870. */
  41871. set: function (value) {
  41872. this._imageProcessingConfiguration.contrast = value;
  41873. },
  41874. enumerable: true,
  41875. configurable: true
  41876. });
  41877. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41878. /**
  41879. * Gets the Color Grading 2D Lookup Texture.
  41880. */
  41881. get: function () {
  41882. return this._imageProcessingConfiguration.colorGradingTexture;
  41883. },
  41884. /**
  41885. * Sets the Color Grading 2D Lookup Texture.
  41886. */
  41887. set: function (value) {
  41888. this._imageProcessingConfiguration.colorGradingTexture = value;
  41889. },
  41890. enumerable: true,
  41891. configurable: true
  41892. });
  41893. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41894. /**
  41895. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41896. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41897. * 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;
  41898. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41899. */
  41900. get: function () {
  41901. return this._imageProcessingConfiguration.colorCurves;
  41902. },
  41903. /**
  41904. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41905. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41906. * 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;
  41907. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41908. */
  41909. set: function (value) {
  41910. this._imageProcessingConfiguration.colorCurves = value;
  41911. },
  41912. enumerable: true,
  41913. configurable: true
  41914. });
  41915. StandardMaterial.prototype.getClassName = function () {
  41916. return "StandardMaterial";
  41917. };
  41918. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41919. get: function () {
  41920. return this._useLogarithmicDepth;
  41921. },
  41922. set: function (value) {
  41923. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41924. this._markAllSubMeshesAsMiscDirty();
  41925. },
  41926. enumerable: true,
  41927. configurable: true
  41928. });
  41929. StandardMaterial.prototype.needAlphaBlending = function () {
  41930. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41931. };
  41932. StandardMaterial.prototype.needAlphaTesting = function () {
  41933. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41934. };
  41935. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41936. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41937. };
  41938. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41939. return this._diffuseTexture;
  41940. };
  41941. /**
  41942. * Child classes can use it to update shaders
  41943. */
  41944. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41945. if (useInstances === void 0) { useInstances = false; }
  41946. if (subMesh.effect && this.isFrozen) {
  41947. if (this._wasPreviouslyReady && subMesh.effect) {
  41948. return true;
  41949. }
  41950. }
  41951. if (!subMesh._materialDefines) {
  41952. subMesh._materialDefines = new StandardMaterialDefines();
  41953. }
  41954. var scene = this.getScene();
  41955. var defines = subMesh._materialDefines;
  41956. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41957. if (defines._renderId === scene.getRenderId()) {
  41958. return true;
  41959. }
  41960. }
  41961. var engine = scene.getEngine();
  41962. // Lights
  41963. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41964. // Textures
  41965. if (defines._areTexturesDirty) {
  41966. defines._needUVs = false;
  41967. defines.MAINUV1 = false;
  41968. defines.MAINUV2 = false;
  41969. if (scene.texturesEnabled) {
  41970. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41971. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41972. return false;
  41973. }
  41974. else {
  41975. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41976. }
  41977. }
  41978. else {
  41979. defines.DIFFUSE = false;
  41980. }
  41981. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41982. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41983. return false;
  41984. }
  41985. else {
  41986. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41987. }
  41988. }
  41989. else {
  41990. defines.AMBIENT = false;
  41991. }
  41992. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41993. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41994. return false;
  41995. }
  41996. else {
  41997. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41998. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41999. }
  42000. }
  42001. else {
  42002. defines.OPACITY = false;
  42003. }
  42004. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42005. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42006. return false;
  42007. }
  42008. else {
  42009. defines._needNormals = true;
  42010. defines.REFLECTION = true;
  42011. defines.ROUGHNESS = (this._roughness > 0);
  42012. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42013. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42014. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42015. switch (this._reflectionTexture.coordinatesMode) {
  42016. case BABYLON.Texture.EXPLICIT_MODE:
  42017. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42018. break;
  42019. case BABYLON.Texture.PLANAR_MODE:
  42020. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42021. break;
  42022. case BABYLON.Texture.PROJECTION_MODE:
  42023. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42024. break;
  42025. case BABYLON.Texture.SKYBOX_MODE:
  42026. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42027. break;
  42028. case BABYLON.Texture.SPHERICAL_MODE:
  42029. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42030. break;
  42031. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42032. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42033. break;
  42034. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42035. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42036. break;
  42037. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42038. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42039. break;
  42040. case BABYLON.Texture.CUBIC_MODE:
  42041. case BABYLON.Texture.INVCUBIC_MODE:
  42042. default:
  42043. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42044. break;
  42045. }
  42046. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42047. }
  42048. }
  42049. else {
  42050. defines.REFLECTION = false;
  42051. }
  42052. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42053. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42054. return false;
  42055. }
  42056. else {
  42057. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42058. }
  42059. }
  42060. else {
  42061. defines.EMISSIVE = false;
  42062. }
  42063. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42064. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42065. return false;
  42066. }
  42067. else {
  42068. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42069. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42070. }
  42071. }
  42072. else {
  42073. defines.LIGHTMAP = false;
  42074. }
  42075. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42076. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42077. return false;
  42078. }
  42079. else {
  42080. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42081. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42082. }
  42083. }
  42084. else {
  42085. defines.SPECULAR = false;
  42086. }
  42087. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42088. // Bump texure can not be not blocking.
  42089. if (!this._bumpTexture.isReady()) {
  42090. return false;
  42091. }
  42092. else {
  42093. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42094. defines.PARALLAX = this._useParallax;
  42095. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42096. }
  42097. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42098. }
  42099. else {
  42100. defines.BUMP = false;
  42101. }
  42102. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42103. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42104. return false;
  42105. }
  42106. else {
  42107. defines._needUVs = true;
  42108. defines.REFRACTION = true;
  42109. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42110. }
  42111. }
  42112. else {
  42113. defines.REFRACTION = false;
  42114. }
  42115. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42116. }
  42117. else {
  42118. defines.DIFFUSE = false;
  42119. defines.AMBIENT = false;
  42120. defines.OPACITY = false;
  42121. defines.REFLECTION = false;
  42122. defines.EMISSIVE = false;
  42123. defines.LIGHTMAP = false;
  42124. defines.BUMP = false;
  42125. defines.REFRACTION = false;
  42126. }
  42127. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42128. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42129. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42130. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42131. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42132. }
  42133. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42134. if (!this._imageProcessingConfiguration.isReady()) {
  42135. return false;
  42136. }
  42137. this._imageProcessingConfiguration.prepareDefines(defines);
  42138. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42139. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42140. }
  42141. if (defines._areFresnelDirty) {
  42142. if (StandardMaterial.FresnelEnabled) {
  42143. // Fresnel
  42144. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42145. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42146. this._reflectionFresnelParameters) {
  42147. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42148. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42149. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42150. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42151. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42152. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42153. defines._needNormals = true;
  42154. defines.FRESNEL = true;
  42155. }
  42156. }
  42157. else {
  42158. defines.FRESNEL = false;
  42159. }
  42160. }
  42161. // Misc.
  42162. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42163. // Attribs
  42164. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42165. // Values that need to be evaluated on every frame
  42166. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42167. // Get correct effect
  42168. if (defines.isDirty) {
  42169. defines.markAsProcessed();
  42170. scene.resetCachedMaterial();
  42171. // Fallbacks
  42172. var fallbacks = new BABYLON.EffectFallbacks();
  42173. if (defines.REFLECTION) {
  42174. fallbacks.addFallback(0, "REFLECTION");
  42175. }
  42176. if (defines.SPECULAR) {
  42177. fallbacks.addFallback(0, "SPECULAR");
  42178. }
  42179. if (defines.BUMP) {
  42180. fallbacks.addFallback(0, "BUMP");
  42181. }
  42182. if (defines.PARALLAX) {
  42183. fallbacks.addFallback(1, "PARALLAX");
  42184. }
  42185. if (defines.PARALLAXOCCLUSION) {
  42186. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42187. }
  42188. if (defines.SPECULAROVERALPHA) {
  42189. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42190. }
  42191. if (defines.FOG) {
  42192. fallbacks.addFallback(1, "FOG");
  42193. }
  42194. if (defines.POINTSIZE) {
  42195. fallbacks.addFallback(0, "POINTSIZE");
  42196. }
  42197. if (defines.LOGARITHMICDEPTH) {
  42198. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42199. }
  42200. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42201. if (defines.SPECULARTERM) {
  42202. fallbacks.addFallback(0, "SPECULARTERM");
  42203. }
  42204. if (defines.DIFFUSEFRESNEL) {
  42205. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42206. }
  42207. if (defines.OPACITYFRESNEL) {
  42208. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42209. }
  42210. if (defines.REFLECTIONFRESNEL) {
  42211. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42212. }
  42213. if (defines.EMISSIVEFRESNEL) {
  42214. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42215. }
  42216. if (defines.FRESNEL) {
  42217. fallbacks.addFallback(4, "FRESNEL");
  42218. }
  42219. //Attributes
  42220. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42221. if (defines.NORMAL) {
  42222. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42223. }
  42224. if (defines.UV1) {
  42225. attribs.push(BABYLON.VertexBuffer.UVKind);
  42226. }
  42227. if (defines.UV2) {
  42228. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42229. }
  42230. if (defines.VERTEXCOLOR) {
  42231. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42232. }
  42233. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42234. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42235. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42236. var shaderName = "default";
  42237. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42238. "vFogInfos", "vFogColor", "pointSize",
  42239. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42240. "mBones",
  42241. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42242. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42243. "vReflectionPosition", "vReflectionSize",
  42244. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42245. ];
  42246. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42247. var uniformBuffers = ["Material", "Scene"];
  42248. if (BABYLON.ImageProcessingConfiguration) {
  42249. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42250. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42251. }
  42252. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42253. uniformsNames: uniforms,
  42254. uniformBuffersNames: uniformBuffers,
  42255. samplers: samplers,
  42256. defines: defines,
  42257. maxSimultaneousLights: this._maxSimultaneousLights
  42258. });
  42259. if (this.customShaderNameResolve) {
  42260. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42261. }
  42262. var join = defines.toString();
  42263. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42264. attributes: attribs,
  42265. uniformsNames: uniforms,
  42266. uniformBuffersNames: uniformBuffers,
  42267. samplers: samplers,
  42268. defines: join,
  42269. fallbacks: fallbacks,
  42270. onCompiled: this.onCompiled,
  42271. onError: this.onError,
  42272. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42273. }, engine), defines);
  42274. this.buildUniformLayout();
  42275. }
  42276. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42277. return false;
  42278. }
  42279. defines._renderId = scene.getRenderId();
  42280. this._wasPreviouslyReady = true;
  42281. return true;
  42282. };
  42283. StandardMaterial.prototype.buildUniformLayout = function () {
  42284. // Order is important !
  42285. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42286. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42287. this._uniformBuffer.addUniform("opacityParts", 4);
  42288. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42289. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42290. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42291. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42292. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42293. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42294. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42295. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42296. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42297. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42298. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42299. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42300. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42301. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42302. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42303. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42304. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42305. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42306. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42307. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42308. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42309. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42310. this._uniformBuffer.addUniform("specularMatrix", 16);
  42311. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42312. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42313. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42314. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42315. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42316. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42317. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42318. this._uniformBuffer.addUniform("pointSize", 1);
  42319. this._uniformBuffer.create();
  42320. };
  42321. StandardMaterial.prototype.unbind = function () {
  42322. if (this._activeEffect) {
  42323. var needFlag = false;
  42324. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42325. this._activeEffect.setTexture("reflection2DSampler", null);
  42326. needFlag = true;
  42327. }
  42328. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42329. this._activeEffect.setTexture("refraction2DSampler", null);
  42330. needFlag = true;
  42331. }
  42332. if (needFlag) {
  42333. this._markAllSubMeshesAsTexturesDirty();
  42334. }
  42335. }
  42336. _super.prototype.unbind.call(this);
  42337. };
  42338. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42339. var scene = this.getScene();
  42340. var defines = subMesh._materialDefines;
  42341. if (!defines) {
  42342. return;
  42343. }
  42344. var effect = subMesh.effect;
  42345. if (!effect) {
  42346. return;
  42347. }
  42348. this._activeEffect = effect;
  42349. // Matrices
  42350. this.bindOnlyWorldMatrix(world);
  42351. // Normal Matrix
  42352. if (defines.OBJECTSPACE_NORMALMAP) {
  42353. world.toNormalMatrix(this._normalMatrix);
  42354. this.bindOnlyNormalMatrix(this._normalMatrix);
  42355. }
  42356. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42357. // Bones
  42358. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42359. if (mustRebind) {
  42360. this._uniformBuffer.bindToEffect(effect, "Material");
  42361. this.bindViewProjection(effect);
  42362. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42363. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42364. // Fresnel
  42365. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42366. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42367. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42368. }
  42369. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42370. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42371. }
  42372. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42373. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42374. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42375. }
  42376. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42377. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42378. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42379. }
  42380. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42381. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42382. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42383. }
  42384. }
  42385. // Textures
  42386. if (scene.texturesEnabled) {
  42387. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42388. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42389. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42390. if (this._diffuseTexture.hasAlpha) {
  42391. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42392. }
  42393. }
  42394. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42395. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42396. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42397. }
  42398. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42399. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42400. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42401. }
  42402. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42403. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42404. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42405. if (this._reflectionTexture.boundingBoxSize) {
  42406. var cubeTexture = this._reflectionTexture;
  42407. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42408. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42409. }
  42410. }
  42411. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42412. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42413. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42414. }
  42415. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42416. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42417. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42418. }
  42419. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42420. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42421. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42422. }
  42423. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42424. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42425. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42426. if (scene._mirroredCameraPosition) {
  42427. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42428. }
  42429. else {
  42430. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42431. }
  42432. }
  42433. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42434. var depth = 1.0;
  42435. if (!this._refractionTexture.isCube) {
  42436. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42437. if (this._refractionTexture.depth) {
  42438. depth = this._refractionTexture.depth;
  42439. }
  42440. }
  42441. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42442. }
  42443. }
  42444. // Point size
  42445. if (this.pointsCloud) {
  42446. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42447. }
  42448. if (defines.SPECULARTERM) {
  42449. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42450. }
  42451. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42452. // Diffuse
  42453. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42454. }
  42455. // Textures
  42456. if (scene.texturesEnabled) {
  42457. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42458. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42459. }
  42460. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42461. effect.setTexture("ambientSampler", this._ambientTexture);
  42462. }
  42463. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42464. effect.setTexture("opacitySampler", this._opacityTexture);
  42465. }
  42466. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42467. if (this._reflectionTexture.isCube) {
  42468. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42469. }
  42470. else {
  42471. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42472. }
  42473. }
  42474. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42475. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42476. }
  42477. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42478. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42479. }
  42480. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42481. effect.setTexture("specularSampler", this._specularTexture);
  42482. }
  42483. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42484. effect.setTexture("bumpSampler", this._bumpTexture);
  42485. }
  42486. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42487. var depth = 1.0;
  42488. if (this._refractionTexture.isCube) {
  42489. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42490. }
  42491. else {
  42492. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42493. }
  42494. }
  42495. }
  42496. // Clip plane
  42497. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42498. // Colors
  42499. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42500. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42501. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42502. }
  42503. if (mustRebind || !this.isFrozen) {
  42504. // Lights
  42505. if (scene.lightsEnabled && !this._disableLighting) {
  42506. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42507. }
  42508. // View
  42509. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42510. this.bindView(effect);
  42511. }
  42512. // Fog
  42513. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42514. // Morph targets
  42515. if (defines.NUM_MORPH_INFLUENCERS) {
  42516. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42517. }
  42518. // Log. depth
  42519. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42520. // image processing
  42521. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42522. this._imageProcessingConfiguration.bind(this._activeEffect);
  42523. }
  42524. }
  42525. this._uniformBuffer.update();
  42526. this._afterBind(mesh, this._activeEffect);
  42527. };
  42528. StandardMaterial.prototype.getAnimatables = function () {
  42529. var results = [];
  42530. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42531. results.push(this._diffuseTexture);
  42532. }
  42533. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42534. results.push(this._ambientTexture);
  42535. }
  42536. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42537. results.push(this._opacityTexture);
  42538. }
  42539. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42540. results.push(this._reflectionTexture);
  42541. }
  42542. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42543. results.push(this._emissiveTexture);
  42544. }
  42545. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42546. results.push(this._specularTexture);
  42547. }
  42548. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42549. results.push(this._bumpTexture);
  42550. }
  42551. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42552. results.push(this._lightmapTexture);
  42553. }
  42554. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42555. results.push(this._refractionTexture);
  42556. }
  42557. return results;
  42558. };
  42559. StandardMaterial.prototype.getActiveTextures = function () {
  42560. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42561. if (this._diffuseTexture) {
  42562. activeTextures.push(this._diffuseTexture);
  42563. }
  42564. if (this._ambientTexture) {
  42565. activeTextures.push(this._ambientTexture);
  42566. }
  42567. if (this._opacityTexture) {
  42568. activeTextures.push(this._opacityTexture);
  42569. }
  42570. if (this._reflectionTexture) {
  42571. activeTextures.push(this._reflectionTexture);
  42572. }
  42573. if (this._emissiveTexture) {
  42574. activeTextures.push(this._emissiveTexture);
  42575. }
  42576. if (this._specularTexture) {
  42577. activeTextures.push(this._specularTexture);
  42578. }
  42579. if (this._bumpTexture) {
  42580. activeTextures.push(this._bumpTexture);
  42581. }
  42582. if (this._lightmapTexture) {
  42583. activeTextures.push(this._lightmapTexture);
  42584. }
  42585. if (this._refractionTexture) {
  42586. activeTextures.push(this._refractionTexture);
  42587. }
  42588. return activeTextures;
  42589. };
  42590. StandardMaterial.prototype.hasTexture = function (texture) {
  42591. if (_super.prototype.hasTexture.call(this, texture)) {
  42592. return true;
  42593. }
  42594. if (this._diffuseTexture === texture) {
  42595. return true;
  42596. }
  42597. if (this._ambientTexture === texture) {
  42598. return true;
  42599. }
  42600. if (this._opacityTexture === texture) {
  42601. return true;
  42602. }
  42603. if (this._reflectionTexture === texture) {
  42604. return true;
  42605. }
  42606. if (this._emissiveTexture === texture) {
  42607. return true;
  42608. }
  42609. if (this._specularTexture === texture) {
  42610. return true;
  42611. }
  42612. if (this._bumpTexture === texture) {
  42613. return true;
  42614. }
  42615. if (this._lightmapTexture === texture) {
  42616. return true;
  42617. }
  42618. if (this._refractionTexture === texture) {
  42619. return true;
  42620. }
  42621. return false;
  42622. };
  42623. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42624. if (forceDisposeTextures) {
  42625. if (this._diffuseTexture) {
  42626. this._diffuseTexture.dispose();
  42627. }
  42628. if (this._ambientTexture) {
  42629. this._ambientTexture.dispose();
  42630. }
  42631. if (this._opacityTexture) {
  42632. this._opacityTexture.dispose();
  42633. }
  42634. if (this._reflectionTexture) {
  42635. this._reflectionTexture.dispose();
  42636. }
  42637. if (this._emissiveTexture) {
  42638. this._emissiveTexture.dispose();
  42639. }
  42640. if (this._specularTexture) {
  42641. this._specularTexture.dispose();
  42642. }
  42643. if (this._bumpTexture) {
  42644. this._bumpTexture.dispose();
  42645. }
  42646. if (this._lightmapTexture) {
  42647. this._lightmapTexture.dispose();
  42648. }
  42649. if (this._refractionTexture) {
  42650. this._refractionTexture.dispose();
  42651. }
  42652. }
  42653. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42654. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42655. }
  42656. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42657. };
  42658. StandardMaterial.prototype.clone = function (name) {
  42659. var _this = this;
  42660. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42661. result.name = name;
  42662. result.id = name;
  42663. return result;
  42664. };
  42665. StandardMaterial.prototype.serialize = function () {
  42666. return BABYLON.SerializationHelper.Serialize(this);
  42667. };
  42668. // Statics
  42669. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42670. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42671. };
  42672. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42673. get: function () {
  42674. return StandardMaterial._DiffuseTextureEnabled;
  42675. },
  42676. set: function (value) {
  42677. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42678. return;
  42679. }
  42680. StandardMaterial._DiffuseTextureEnabled = value;
  42681. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42682. },
  42683. enumerable: true,
  42684. configurable: true
  42685. });
  42686. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42687. get: function () {
  42688. return StandardMaterial._AmbientTextureEnabled;
  42689. },
  42690. set: function (value) {
  42691. if (StandardMaterial._AmbientTextureEnabled === value) {
  42692. return;
  42693. }
  42694. StandardMaterial._AmbientTextureEnabled = value;
  42695. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42696. },
  42697. enumerable: true,
  42698. configurable: true
  42699. });
  42700. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42701. get: function () {
  42702. return StandardMaterial._OpacityTextureEnabled;
  42703. },
  42704. set: function (value) {
  42705. if (StandardMaterial._OpacityTextureEnabled === value) {
  42706. return;
  42707. }
  42708. StandardMaterial._OpacityTextureEnabled = value;
  42709. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42710. },
  42711. enumerable: true,
  42712. configurable: true
  42713. });
  42714. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42715. get: function () {
  42716. return StandardMaterial._ReflectionTextureEnabled;
  42717. },
  42718. set: function (value) {
  42719. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42720. return;
  42721. }
  42722. StandardMaterial._ReflectionTextureEnabled = value;
  42723. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42724. },
  42725. enumerable: true,
  42726. configurable: true
  42727. });
  42728. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42729. get: function () {
  42730. return StandardMaterial._EmissiveTextureEnabled;
  42731. },
  42732. set: function (value) {
  42733. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42734. return;
  42735. }
  42736. StandardMaterial._EmissiveTextureEnabled = value;
  42737. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42738. },
  42739. enumerable: true,
  42740. configurable: true
  42741. });
  42742. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42743. get: function () {
  42744. return StandardMaterial._SpecularTextureEnabled;
  42745. },
  42746. set: function (value) {
  42747. if (StandardMaterial._SpecularTextureEnabled === value) {
  42748. return;
  42749. }
  42750. StandardMaterial._SpecularTextureEnabled = value;
  42751. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42752. },
  42753. enumerable: true,
  42754. configurable: true
  42755. });
  42756. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42757. get: function () {
  42758. return StandardMaterial._BumpTextureEnabled;
  42759. },
  42760. set: function (value) {
  42761. if (StandardMaterial._BumpTextureEnabled === value) {
  42762. return;
  42763. }
  42764. StandardMaterial._BumpTextureEnabled = value;
  42765. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42766. },
  42767. enumerable: true,
  42768. configurable: true
  42769. });
  42770. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42771. get: function () {
  42772. return StandardMaterial._LightmapTextureEnabled;
  42773. },
  42774. set: function (value) {
  42775. if (StandardMaterial._LightmapTextureEnabled === value) {
  42776. return;
  42777. }
  42778. StandardMaterial._LightmapTextureEnabled = value;
  42779. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42780. },
  42781. enumerable: true,
  42782. configurable: true
  42783. });
  42784. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42785. get: function () {
  42786. return StandardMaterial._RefractionTextureEnabled;
  42787. },
  42788. set: function (value) {
  42789. if (StandardMaterial._RefractionTextureEnabled === value) {
  42790. return;
  42791. }
  42792. StandardMaterial._RefractionTextureEnabled = value;
  42793. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42794. },
  42795. enumerable: true,
  42796. configurable: true
  42797. });
  42798. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42799. get: function () {
  42800. return StandardMaterial._ColorGradingTextureEnabled;
  42801. },
  42802. set: function (value) {
  42803. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42804. return;
  42805. }
  42806. StandardMaterial._ColorGradingTextureEnabled = value;
  42807. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42808. },
  42809. enumerable: true,
  42810. configurable: true
  42811. });
  42812. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42813. get: function () {
  42814. return StandardMaterial._FresnelEnabled;
  42815. },
  42816. set: function (value) {
  42817. if (StandardMaterial._FresnelEnabled === value) {
  42818. return;
  42819. }
  42820. StandardMaterial._FresnelEnabled = value;
  42821. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42822. },
  42823. enumerable: true,
  42824. configurable: true
  42825. });
  42826. // Flags used to enable or disable a type of texture for all Standard Materials
  42827. StandardMaterial._DiffuseTextureEnabled = true;
  42828. StandardMaterial._AmbientTextureEnabled = true;
  42829. StandardMaterial._OpacityTextureEnabled = true;
  42830. StandardMaterial._ReflectionTextureEnabled = true;
  42831. StandardMaterial._EmissiveTextureEnabled = true;
  42832. StandardMaterial._SpecularTextureEnabled = true;
  42833. StandardMaterial._BumpTextureEnabled = true;
  42834. StandardMaterial._LightmapTextureEnabled = true;
  42835. StandardMaterial._RefractionTextureEnabled = true;
  42836. StandardMaterial._ColorGradingTextureEnabled = true;
  42837. StandardMaterial._FresnelEnabled = true;
  42838. __decorate([
  42839. BABYLON.serializeAsTexture("diffuseTexture")
  42840. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42841. __decorate([
  42842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42843. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42844. __decorate([
  42845. BABYLON.serializeAsTexture("ambientTexture")
  42846. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42847. __decorate([
  42848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42849. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42850. __decorate([
  42851. BABYLON.serializeAsTexture("opacityTexture")
  42852. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42853. __decorate([
  42854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42855. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42856. __decorate([
  42857. BABYLON.serializeAsTexture("reflectionTexture")
  42858. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42859. __decorate([
  42860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42861. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42862. __decorate([
  42863. BABYLON.serializeAsTexture("emissiveTexture")
  42864. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42865. __decorate([
  42866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42867. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42868. __decorate([
  42869. BABYLON.serializeAsTexture("specularTexture")
  42870. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42871. __decorate([
  42872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42873. ], StandardMaterial.prototype, "specularTexture", void 0);
  42874. __decorate([
  42875. BABYLON.serializeAsTexture("bumpTexture")
  42876. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42877. __decorate([
  42878. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42879. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42880. __decorate([
  42881. BABYLON.serializeAsTexture("lightmapTexture")
  42882. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42883. __decorate([
  42884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42885. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42886. __decorate([
  42887. BABYLON.serializeAsTexture("refractionTexture")
  42888. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42889. __decorate([
  42890. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42891. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42892. __decorate([
  42893. BABYLON.serializeAsColor3("ambient")
  42894. ], StandardMaterial.prototype, "ambientColor", void 0);
  42895. __decorate([
  42896. BABYLON.serializeAsColor3("diffuse")
  42897. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42898. __decorate([
  42899. BABYLON.serializeAsColor3("specular")
  42900. ], StandardMaterial.prototype, "specularColor", void 0);
  42901. __decorate([
  42902. BABYLON.serializeAsColor3("emissive")
  42903. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42904. __decorate([
  42905. BABYLON.serialize()
  42906. ], StandardMaterial.prototype, "specularPower", void 0);
  42907. __decorate([
  42908. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42909. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42910. __decorate([
  42911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42912. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42913. __decorate([
  42914. BABYLON.serialize("useEmissiveAsIllumination")
  42915. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42916. __decorate([
  42917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42918. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42919. __decorate([
  42920. BABYLON.serialize("linkEmissiveWithDiffuse")
  42921. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42922. __decorate([
  42923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42924. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42925. __decorate([
  42926. BABYLON.serialize("useSpecularOverAlpha")
  42927. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42928. __decorate([
  42929. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42930. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42931. __decorate([
  42932. BABYLON.serialize("useReflectionOverAlpha")
  42933. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42934. __decorate([
  42935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42936. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42937. __decorate([
  42938. BABYLON.serialize("disableLighting")
  42939. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42940. __decorate([
  42941. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42942. ], StandardMaterial.prototype, "disableLighting", void 0);
  42943. __decorate([
  42944. BABYLON.serialize("useObjectSpaceNormalMap")
  42945. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42946. __decorate([
  42947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42948. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42949. __decorate([
  42950. BABYLON.serialize("useParallax")
  42951. ], StandardMaterial.prototype, "_useParallax", void 0);
  42952. __decorate([
  42953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42954. ], StandardMaterial.prototype, "useParallax", void 0);
  42955. __decorate([
  42956. BABYLON.serialize("useParallaxOcclusion")
  42957. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42958. __decorate([
  42959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42960. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42961. __decorate([
  42962. BABYLON.serialize()
  42963. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42964. __decorate([
  42965. BABYLON.serialize("roughness")
  42966. ], StandardMaterial.prototype, "_roughness", void 0);
  42967. __decorate([
  42968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42969. ], StandardMaterial.prototype, "roughness", void 0);
  42970. __decorate([
  42971. BABYLON.serialize()
  42972. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42973. __decorate([
  42974. BABYLON.serialize()
  42975. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42976. __decorate([
  42977. BABYLON.serialize()
  42978. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42979. __decorate([
  42980. BABYLON.serialize("useLightmapAsShadowmap")
  42981. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42982. __decorate([
  42983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42984. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42985. __decorate([
  42986. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42987. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42988. __decorate([
  42989. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42990. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42991. __decorate([
  42992. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42993. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42994. __decorate([
  42995. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42996. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42997. __decorate([
  42998. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42999. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43000. __decorate([
  43001. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43002. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43003. __decorate([
  43004. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43005. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43006. __decorate([
  43007. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43008. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43009. __decorate([
  43010. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43011. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43012. __decorate([
  43013. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43014. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43015. __decorate([
  43016. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43017. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43018. __decorate([
  43019. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43020. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43021. __decorate([
  43022. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43023. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43024. __decorate([
  43025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43026. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43027. __decorate([
  43028. BABYLON.serialize("maxSimultaneousLights")
  43029. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43030. __decorate([
  43031. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43032. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43033. __decorate([
  43034. BABYLON.serialize("invertNormalMapX")
  43035. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43036. __decorate([
  43037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43038. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43039. __decorate([
  43040. BABYLON.serialize("invertNormalMapY")
  43041. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43042. __decorate([
  43043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43044. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43045. __decorate([
  43046. BABYLON.serialize("twoSidedLighting")
  43047. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43048. __decorate([
  43049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43050. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43051. __decorate([
  43052. BABYLON.serialize()
  43053. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43054. return StandardMaterial;
  43055. }(BABYLON.PushMaterial));
  43056. BABYLON.StandardMaterial = StandardMaterial;
  43057. })(BABYLON || (BABYLON = {}));
  43058. //# sourceMappingURL=babylon.standardMaterial.js.map
  43059. var BABYLON;
  43060. (function (BABYLON) {
  43061. /**
  43062. * Manages the defines for the PBR Material.
  43063. * @hiddenChildren
  43064. */
  43065. var PBRMaterialDefines = /** @class */ (function (_super) {
  43066. __extends(PBRMaterialDefines, _super);
  43067. /**
  43068. * Initializes the PBR Material defines.
  43069. */
  43070. function PBRMaterialDefines() {
  43071. var _this = _super.call(this) || this;
  43072. _this.PBR = true;
  43073. _this.MAINUV1 = false;
  43074. _this.MAINUV2 = false;
  43075. _this.UV1 = false;
  43076. _this.UV2 = false;
  43077. _this.ALBEDO = false;
  43078. _this.ALBEDODIRECTUV = 0;
  43079. _this.VERTEXCOLOR = false;
  43080. _this.AMBIENT = false;
  43081. _this.AMBIENTDIRECTUV = 0;
  43082. _this.AMBIENTINGRAYSCALE = false;
  43083. _this.OPACITY = false;
  43084. _this.VERTEXALPHA = false;
  43085. _this.OPACITYDIRECTUV = 0;
  43086. _this.OPACITYRGB = false;
  43087. _this.ALPHATEST = false;
  43088. _this.DEPTHPREPASS = false;
  43089. _this.ALPHABLEND = false;
  43090. _this.ALPHAFROMALBEDO = false;
  43091. _this.ALPHATESTVALUE = "0.5";
  43092. _this.SPECULAROVERALPHA = false;
  43093. _this.RADIANCEOVERALPHA = false;
  43094. _this.ALPHAFRESNEL = false;
  43095. _this.LINEARALPHAFRESNEL = false;
  43096. _this.PREMULTIPLYALPHA = false;
  43097. _this.EMISSIVE = false;
  43098. _this.EMISSIVEDIRECTUV = 0;
  43099. _this.REFLECTIVITY = false;
  43100. _this.REFLECTIVITYDIRECTUV = 0;
  43101. _this.SPECULARTERM = false;
  43102. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43103. _this.MICROSURFACEAUTOMATIC = false;
  43104. _this.LODBASEDMICROSFURACE = false;
  43105. _this.MICROSURFACEMAP = false;
  43106. _this.MICROSURFACEMAPDIRECTUV = 0;
  43107. _this.METALLICWORKFLOW = false;
  43108. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43109. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43110. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43111. _this.AOSTOREINMETALMAPRED = false;
  43112. _this.ENVIRONMENTBRDF = false;
  43113. _this.NORMAL = false;
  43114. _this.TANGENT = false;
  43115. _this.BUMP = false;
  43116. _this.BUMPDIRECTUV = 0;
  43117. _this.OBJECTSPACE_NORMALMAP = false;
  43118. _this.PARALLAX = false;
  43119. _this.PARALLAXOCCLUSION = false;
  43120. _this.NORMALXYSCALE = true;
  43121. _this.LIGHTMAP = false;
  43122. _this.LIGHTMAPDIRECTUV = 0;
  43123. _this.USELIGHTMAPASSHADOWMAP = false;
  43124. _this.GAMMALIGHTMAP = false;
  43125. _this.REFLECTION = false;
  43126. _this.REFLECTIONMAP_3D = false;
  43127. _this.REFLECTIONMAP_SPHERICAL = false;
  43128. _this.REFLECTIONMAP_PLANAR = false;
  43129. _this.REFLECTIONMAP_CUBIC = false;
  43130. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43131. _this.REFLECTIONMAP_PROJECTION = false;
  43132. _this.REFLECTIONMAP_SKYBOX = false;
  43133. _this.REFLECTIONMAP_EXPLICIT = false;
  43134. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43135. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43136. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43137. _this.INVERTCUBICMAP = false;
  43138. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43139. _this.USESPHERICALINVERTEX = false;
  43140. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43141. _this.LODINREFLECTIONALPHA = false;
  43142. _this.GAMMAREFLECTION = false;
  43143. _this.RGBDREFLECTION = false;
  43144. _this.RADIANCEOCCLUSION = false;
  43145. _this.HORIZONOCCLUSION = false;
  43146. _this.REFRACTION = false;
  43147. _this.REFRACTIONMAP_3D = false;
  43148. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43149. _this.LODINREFRACTIONALPHA = false;
  43150. _this.GAMMAREFRACTION = false;
  43151. _this.RGBDREFRACTION = false;
  43152. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43153. _this.INSTANCES = false;
  43154. _this.NUM_BONE_INFLUENCERS = 0;
  43155. _this.BonesPerMesh = 0;
  43156. _this.NONUNIFORMSCALING = false;
  43157. _this.MORPHTARGETS = false;
  43158. _this.MORPHTARGETS_NORMAL = false;
  43159. _this.MORPHTARGETS_TANGENT = false;
  43160. _this.NUM_MORPH_INFLUENCERS = 0;
  43161. _this.IMAGEPROCESSING = false;
  43162. _this.VIGNETTE = false;
  43163. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43164. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43165. _this.TONEMAPPING = false;
  43166. _this.CONTRAST = false;
  43167. _this.COLORCURVES = false;
  43168. _this.COLORGRADING = false;
  43169. _this.COLORGRADING3D = false;
  43170. _this.SAMPLER3DGREENDEPTH = false;
  43171. _this.SAMPLER3DBGRMAP = false;
  43172. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43173. _this.EXPOSURE = false;
  43174. _this.USEPHYSICALLIGHTFALLOFF = false;
  43175. _this.TWOSIDEDLIGHTING = false;
  43176. _this.SHADOWFLOAT = false;
  43177. _this.CLIPPLANE = false;
  43178. _this.POINTSIZE = false;
  43179. _this.FOG = false;
  43180. _this.LOGARITHMICDEPTH = false;
  43181. _this.FORCENORMALFORWARD = false;
  43182. _this.SPECULARAA = false;
  43183. _this.UNLIT = false;
  43184. _this.rebuild();
  43185. return _this;
  43186. }
  43187. /**
  43188. * Resets the PBR Material defines.
  43189. */
  43190. PBRMaterialDefines.prototype.reset = function () {
  43191. _super.prototype.reset.call(this);
  43192. this.ALPHATESTVALUE = "0.5";
  43193. this.PBR = true;
  43194. };
  43195. return PBRMaterialDefines;
  43196. }(BABYLON.MaterialDefines));
  43197. /**
  43198. * The Physically based material base class of BJS.
  43199. *
  43200. * This offers the main features of a standard PBR material.
  43201. * For more information, please refer to the documentation :
  43202. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43203. */
  43204. var PBRBaseMaterial = /** @class */ (function (_super) {
  43205. __extends(PBRBaseMaterial, _super);
  43206. /**
  43207. * Instantiates a new PBRMaterial instance.
  43208. *
  43209. * @param name The material name
  43210. * @param scene The scene the material will be use in.
  43211. */
  43212. function PBRBaseMaterial(name, scene) {
  43213. var _this = _super.call(this, name, scene) || this;
  43214. /**
  43215. * Intensity of the direct lights e.g. the four lights available in your scene.
  43216. * This impacts both the direct diffuse and specular highlights.
  43217. */
  43218. _this._directIntensity = 1.0;
  43219. /**
  43220. * Intensity of the emissive part of the material.
  43221. * This helps controlling the emissive effect without modifying the emissive color.
  43222. */
  43223. _this._emissiveIntensity = 1.0;
  43224. /**
  43225. * Intensity of the environment e.g. how much the environment will light the object
  43226. * either through harmonics for rough material or through the refelction for shiny ones.
  43227. */
  43228. _this._environmentIntensity = 1.0;
  43229. /**
  43230. * This is a special control allowing the reduction of the specular highlights coming from the
  43231. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43232. */
  43233. _this._specularIntensity = 1.0;
  43234. /**
  43235. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43236. */
  43237. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43238. /**
  43239. * Debug Control allowing disabling the bump map on this material.
  43240. */
  43241. _this._disableBumpMap = false;
  43242. /**
  43243. * AKA Occlusion Texture Intensity in other nomenclature.
  43244. */
  43245. _this._ambientTextureStrength = 1.0;
  43246. /**
  43247. * The color of a material in ambient lighting.
  43248. */
  43249. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43250. /**
  43251. * AKA Diffuse Color in other nomenclature.
  43252. */
  43253. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43254. /**
  43255. * AKA Specular Color in other nomenclature.
  43256. */
  43257. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43258. /**
  43259. * The color applied when light is reflected from a material.
  43260. */
  43261. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43262. /**
  43263. * The color applied when light is emitted from a material.
  43264. */
  43265. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43266. /**
  43267. * AKA Glossiness in other nomenclature.
  43268. */
  43269. _this._microSurface = 0.9;
  43270. /**
  43271. * source material index of refraction (IOR)' / 'destination material IOR.
  43272. */
  43273. _this._indexOfRefraction = 0.66;
  43274. /**
  43275. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43276. */
  43277. _this._invertRefractionY = false;
  43278. /**
  43279. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43280. * Materials half opaque for instance using refraction could benefit from this control.
  43281. */
  43282. _this._linkRefractionWithTransparency = false;
  43283. /**
  43284. * Specifies that the material will use the light map as a show map.
  43285. */
  43286. _this._useLightmapAsShadowmap = false;
  43287. /**
  43288. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43289. * makes the reflect vector face the model (under horizon).
  43290. */
  43291. _this._useHorizonOcclusion = true;
  43292. /**
  43293. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43294. * too much the area relying on ambient texture to define their ambient occlusion.
  43295. */
  43296. _this._useRadianceOcclusion = true;
  43297. /**
  43298. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43299. */
  43300. _this._useAlphaFromAlbedoTexture = false;
  43301. /**
  43302. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43303. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43304. */
  43305. _this._useSpecularOverAlpha = true;
  43306. /**
  43307. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43308. */
  43309. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43310. /**
  43311. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43312. */
  43313. _this._useRoughnessFromMetallicTextureAlpha = true;
  43314. /**
  43315. * Specifies if the metallic texture contains the roughness information in its green channel.
  43316. */
  43317. _this._useRoughnessFromMetallicTextureGreen = false;
  43318. /**
  43319. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43320. */
  43321. _this._useMetallnessFromMetallicTextureBlue = false;
  43322. /**
  43323. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43324. */
  43325. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43326. /**
  43327. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43328. */
  43329. _this._useAmbientInGrayScale = false;
  43330. /**
  43331. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43332. * The material will try to infer what glossiness each pixel should be.
  43333. */
  43334. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43335. /**
  43336. * BJS is using an harcoded light falloff based on a manually sets up range.
  43337. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43338. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43339. */
  43340. _this._usePhysicalLightFalloff = true;
  43341. /**
  43342. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43343. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43344. */
  43345. _this._useRadianceOverAlpha = true;
  43346. /**
  43347. * Allows using an object space normal map (instead of tangent space).
  43348. */
  43349. _this._useObjectSpaceNormalMap = false;
  43350. /**
  43351. * Allows using the bump map in parallax mode.
  43352. */
  43353. _this._useParallax = false;
  43354. /**
  43355. * Allows using the bump map in parallax occlusion mode.
  43356. */
  43357. _this._useParallaxOcclusion = false;
  43358. /**
  43359. * Controls the scale bias of the parallax mode.
  43360. */
  43361. _this._parallaxScaleBias = 0.05;
  43362. /**
  43363. * If sets to true, disables all the lights affecting the material.
  43364. */
  43365. _this._disableLighting = false;
  43366. /**
  43367. * Number of Simultaneous lights allowed on the material.
  43368. */
  43369. _this._maxSimultaneousLights = 4;
  43370. /**
  43371. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43372. */
  43373. _this._invertNormalMapX = false;
  43374. /**
  43375. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43376. */
  43377. _this._invertNormalMapY = false;
  43378. /**
  43379. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43380. */
  43381. _this._twoSidedLighting = false;
  43382. /**
  43383. * Defines the alpha limits in alpha test mode.
  43384. */
  43385. _this._alphaCutOff = 0.4;
  43386. /**
  43387. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43388. */
  43389. _this._forceAlphaTest = false;
  43390. /**
  43391. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43392. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43393. */
  43394. _this._useAlphaFresnel = false;
  43395. /**
  43396. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43397. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43398. */
  43399. _this._useLinearAlphaFresnel = false;
  43400. /**
  43401. * The transparency mode of the material.
  43402. */
  43403. _this._transparencyMode = null;
  43404. /**
  43405. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43406. * from cos thetav and roughness:
  43407. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43408. */
  43409. _this._environmentBRDFTexture = null;
  43410. /**
  43411. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43412. */
  43413. _this._forceIrradianceInFragment = false;
  43414. /**
  43415. * Force normal to face away from face.
  43416. */
  43417. _this._forceNormalForward = false;
  43418. /**
  43419. * Enables specular anti aliasing in the PBR shader.
  43420. * It will both interacts on the Geometry for analytical and IBL lighting.
  43421. * It also prefilter the roughness map based on the bump values.
  43422. */
  43423. _this._enableSpecularAntiAliasing = false;
  43424. /**
  43425. * Stores the available render targets.
  43426. */
  43427. _this._renderTargets = new BABYLON.SmartArray(16);
  43428. /**
  43429. * Sets the global ambient color for the material used in lighting calculations.
  43430. */
  43431. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43432. /**
  43433. * If set to true, no lighting calculations will be applied.
  43434. */
  43435. _this._unlit = false;
  43436. // Setup the default processing configuration to the scene.
  43437. _this._attachImageProcessingConfiguration(null);
  43438. _this.getRenderTargetTextures = function () {
  43439. _this._renderTargets.reset();
  43440. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43441. _this._renderTargets.push(_this._reflectionTexture);
  43442. }
  43443. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43444. _this._renderTargets.push(_this._refractionTexture);
  43445. }
  43446. return _this._renderTargets;
  43447. };
  43448. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43449. return _this;
  43450. }
  43451. /**
  43452. * Attaches a new image processing configuration to the PBR Material.
  43453. * @param configuration
  43454. */
  43455. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43456. var _this = this;
  43457. if (configuration === this._imageProcessingConfiguration) {
  43458. return;
  43459. }
  43460. // Detaches observer.
  43461. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43462. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43463. }
  43464. // Pick the scene configuration if needed.
  43465. if (!configuration) {
  43466. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43467. }
  43468. else {
  43469. this._imageProcessingConfiguration = configuration;
  43470. }
  43471. // Attaches observer.
  43472. if (this._imageProcessingConfiguration) {
  43473. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43474. _this._markAllSubMeshesAsImageProcessingDirty();
  43475. });
  43476. }
  43477. };
  43478. /**
  43479. * Gets the name of the material class.
  43480. */
  43481. PBRBaseMaterial.prototype.getClassName = function () {
  43482. return "PBRBaseMaterial";
  43483. };
  43484. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43485. /**
  43486. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43487. */
  43488. get: function () {
  43489. return this._useLogarithmicDepth;
  43490. },
  43491. /**
  43492. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43493. */
  43494. set: function (value) {
  43495. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43496. },
  43497. enumerable: true,
  43498. configurable: true
  43499. });
  43500. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43501. /**
  43502. * Gets the current transparency mode.
  43503. */
  43504. get: function () {
  43505. return this._transparencyMode;
  43506. },
  43507. /**
  43508. * Sets the transparency mode of the material.
  43509. *
  43510. * | Value | Type | Description |
  43511. * | ----- | ----------------------------------- | ----------- |
  43512. * | 0 | OPAQUE | |
  43513. * | 1 | ALPHATEST | |
  43514. * | 2 | ALPHABLEND | |
  43515. * | 3 | ALPHATESTANDBLEND | |
  43516. *
  43517. */
  43518. set: function (value) {
  43519. if (this._transparencyMode === value) {
  43520. return;
  43521. }
  43522. this._transparencyMode = value;
  43523. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43524. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43525. },
  43526. enumerable: true,
  43527. configurable: true
  43528. });
  43529. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43530. /**
  43531. * Returns true if alpha blending should be disabled.
  43532. */
  43533. get: function () {
  43534. return (this._linkRefractionWithTransparency ||
  43535. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43536. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43537. },
  43538. enumerable: true,
  43539. configurable: true
  43540. });
  43541. /**
  43542. * Specifies whether or not this material should be rendered in alpha blend mode.
  43543. */
  43544. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43545. if (this._disableAlphaBlending) {
  43546. return false;
  43547. }
  43548. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43549. };
  43550. /**
  43551. * Specifies if the mesh will require alpha blending.
  43552. * @param mesh - BJS mesh.
  43553. */
  43554. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43555. if (this._disableAlphaBlending) {
  43556. return false;
  43557. }
  43558. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43559. };
  43560. /**
  43561. * Specifies whether or not this material should be rendered in alpha test mode.
  43562. */
  43563. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43564. if (this._forceAlphaTest) {
  43565. return true;
  43566. }
  43567. if (this._linkRefractionWithTransparency) {
  43568. return false;
  43569. }
  43570. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43571. };
  43572. /**
  43573. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43574. */
  43575. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43576. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43577. };
  43578. /**
  43579. * Gets the texture used for the alpha test.
  43580. */
  43581. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43582. return this._albedoTexture;
  43583. };
  43584. /**
  43585. * Specifies that the submesh is ready to be used.
  43586. * @param mesh - BJS mesh.
  43587. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43588. * @param useInstances - Specifies that instances should be used.
  43589. * @returns - boolean indicating that the submesh is ready or not.
  43590. */
  43591. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43592. if (subMesh.effect && this.isFrozen) {
  43593. if (this._wasPreviouslyReady) {
  43594. return true;
  43595. }
  43596. }
  43597. if (!subMesh._materialDefines) {
  43598. subMesh._materialDefines = new PBRMaterialDefines();
  43599. }
  43600. var defines = subMesh._materialDefines;
  43601. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43602. if (defines._renderId === this.getScene().getRenderId()) {
  43603. return true;
  43604. }
  43605. }
  43606. var scene = this.getScene();
  43607. var engine = scene.getEngine();
  43608. if (defines._areTexturesDirty) {
  43609. if (scene.texturesEnabled) {
  43610. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43611. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43612. return false;
  43613. }
  43614. }
  43615. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43616. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43617. return false;
  43618. }
  43619. }
  43620. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43621. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43622. return false;
  43623. }
  43624. }
  43625. var reflectionTexture = this._getReflectionTexture();
  43626. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43627. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43628. return false;
  43629. }
  43630. }
  43631. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43632. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43633. return false;
  43634. }
  43635. }
  43636. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43637. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43638. return false;
  43639. }
  43640. }
  43641. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43642. if (this._metallicTexture) {
  43643. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43644. return false;
  43645. }
  43646. }
  43647. else if (this._reflectivityTexture) {
  43648. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43649. return false;
  43650. }
  43651. }
  43652. if (this._microSurfaceTexture) {
  43653. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43654. return false;
  43655. }
  43656. }
  43657. }
  43658. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43659. // Bump texture cannot be not blocking.
  43660. if (!this._bumpTexture.isReady()) {
  43661. return false;
  43662. }
  43663. }
  43664. var refractionTexture = this._getRefractionTexture();
  43665. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43666. if (!refractionTexture.isReadyOrNotBlocking()) {
  43667. return false;
  43668. }
  43669. }
  43670. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43671. // This is blocking.
  43672. if (!this._environmentBRDFTexture.isReady()) {
  43673. return false;
  43674. }
  43675. }
  43676. }
  43677. }
  43678. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43679. if (!this._imageProcessingConfiguration.isReady()) {
  43680. return false;
  43681. }
  43682. }
  43683. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43684. mesh.createNormals(true);
  43685. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43686. }
  43687. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43688. if (effect) {
  43689. scene.resetCachedMaterial();
  43690. subMesh.setEffect(effect, defines);
  43691. this.buildUniformLayout();
  43692. }
  43693. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43694. return false;
  43695. }
  43696. defines._renderId = scene.getRenderId();
  43697. this._wasPreviouslyReady = true;
  43698. return true;
  43699. };
  43700. /**
  43701. * Specifies if the material uses metallic roughness workflow.
  43702. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43703. */
  43704. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43705. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43706. return true;
  43707. }
  43708. return false;
  43709. };
  43710. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43711. if (onCompiled === void 0) { onCompiled = null; }
  43712. if (onError === void 0) { onError = null; }
  43713. if (useInstances === void 0) { useInstances = null; }
  43714. if (useClipPlane === void 0) { useClipPlane = null; }
  43715. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43716. if (!defines.isDirty) {
  43717. return null;
  43718. }
  43719. defines.markAsProcessed();
  43720. var scene = this.getScene();
  43721. var engine = scene.getEngine();
  43722. // Fallbacks
  43723. var fallbacks = new BABYLON.EffectFallbacks();
  43724. var fallbackRank = 0;
  43725. if (defines.USESPHERICALINVERTEX) {
  43726. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43727. }
  43728. if (defines.FOG) {
  43729. fallbacks.addFallback(fallbackRank, "FOG");
  43730. }
  43731. if (defines.SPECULARAA) {
  43732. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43733. }
  43734. if (defines.POINTSIZE) {
  43735. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43736. }
  43737. if (defines.LOGARITHMICDEPTH) {
  43738. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43739. }
  43740. if (defines.PARALLAX) {
  43741. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43742. }
  43743. if (defines.PARALLAXOCCLUSION) {
  43744. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43745. }
  43746. if (defines.ENVIRONMENTBRDF) {
  43747. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43748. }
  43749. if (defines.TANGENT) {
  43750. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43751. }
  43752. if (defines.BUMP) {
  43753. fallbacks.addFallback(fallbackRank++, "BUMP");
  43754. }
  43755. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43756. if (defines.SPECULARTERM) {
  43757. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43758. }
  43759. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43760. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43761. }
  43762. if (defines.LIGHTMAP) {
  43763. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43764. }
  43765. if (defines.NORMAL) {
  43766. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43767. }
  43768. if (defines.AMBIENT) {
  43769. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43770. }
  43771. if (defines.EMISSIVE) {
  43772. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43773. }
  43774. if (defines.VERTEXCOLOR) {
  43775. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43776. }
  43777. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43778. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43779. }
  43780. if (defines.MORPHTARGETS) {
  43781. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43782. }
  43783. //Attributes
  43784. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43785. if (defines.NORMAL) {
  43786. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43787. }
  43788. if (defines.TANGENT) {
  43789. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43790. }
  43791. if (defines.UV1) {
  43792. attribs.push(BABYLON.VertexBuffer.UVKind);
  43793. }
  43794. if (defines.UV2) {
  43795. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43796. }
  43797. if (defines.VERTEXCOLOR) {
  43798. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43799. }
  43800. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43801. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43802. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43803. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43804. "vFogInfos", "vFogColor", "pointSize",
  43805. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43806. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43807. "mBones",
  43808. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43809. "vLightingIntensity",
  43810. "logarithmicDepthConstant",
  43811. "vSphericalX", "vSphericalY", "vSphericalZ",
  43812. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43813. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43814. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43815. "vTangentSpaceParams"
  43816. ];
  43817. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43818. "bumpSampler", "lightmapSampler", "opacitySampler",
  43819. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43820. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43821. "microSurfaceSampler", "environmentBrdfSampler"];
  43822. var uniformBuffers = ["Material", "Scene"];
  43823. if (BABYLON.ImageProcessingConfiguration) {
  43824. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43825. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43826. }
  43827. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43828. uniformsNames: uniforms,
  43829. uniformBuffersNames: uniformBuffers,
  43830. samplers: samplers,
  43831. defines: defines,
  43832. maxSimultaneousLights: this._maxSimultaneousLights
  43833. });
  43834. var join = defines.toString();
  43835. return engine.createEffect("pbr", {
  43836. attributes: attribs,
  43837. uniformsNames: uniforms,
  43838. uniformBuffersNames: uniformBuffers,
  43839. samplers: samplers,
  43840. defines: join,
  43841. fallbacks: fallbacks,
  43842. onCompiled: onCompiled,
  43843. onError: onError,
  43844. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43845. }, engine);
  43846. };
  43847. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43848. if (useInstances === void 0) { useInstances = null; }
  43849. if (useClipPlane === void 0) { useClipPlane = null; }
  43850. var scene = this.getScene();
  43851. var engine = scene.getEngine();
  43852. // Lights
  43853. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43854. defines._needNormals = true;
  43855. // Textures
  43856. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43857. if (defines._areTexturesDirty) {
  43858. defines._needUVs = false;
  43859. if (scene.texturesEnabled) {
  43860. if (scene.getEngine().getCaps().textureLOD) {
  43861. defines.LODBASEDMICROSFURACE = true;
  43862. }
  43863. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43864. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  43865. }
  43866. else {
  43867. defines.ALBEDO = false;
  43868. }
  43869. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43870. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43871. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  43872. }
  43873. else {
  43874. defines.AMBIENT = false;
  43875. }
  43876. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43877. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43878. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43879. }
  43880. else {
  43881. defines.OPACITY = false;
  43882. }
  43883. var reflectionTexture = this._getReflectionTexture();
  43884. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43885. defines.REFLECTION = true;
  43886. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  43887. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  43888. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  43889. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  43890. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  43891. defines.INVERTCUBICMAP = true;
  43892. }
  43893. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  43894. switch (reflectionTexture.coordinatesMode) {
  43895. case BABYLON.Texture.EXPLICIT_MODE:
  43896. defines.REFLECTIONMAP_EXPLICIT = true;
  43897. break;
  43898. case BABYLON.Texture.PLANAR_MODE:
  43899. defines.REFLECTIONMAP_PLANAR = true;
  43900. break;
  43901. case BABYLON.Texture.PROJECTION_MODE:
  43902. defines.REFLECTIONMAP_PROJECTION = true;
  43903. break;
  43904. case BABYLON.Texture.SKYBOX_MODE:
  43905. defines.REFLECTIONMAP_SKYBOX = true;
  43906. break;
  43907. case BABYLON.Texture.SPHERICAL_MODE:
  43908. defines.REFLECTIONMAP_SPHERICAL = true;
  43909. break;
  43910. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43911. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  43912. break;
  43913. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43914. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  43915. break;
  43916. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43917. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  43918. break;
  43919. case BABYLON.Texture.CUBIC_MODE:
  43920. case BABYLON.Texture.INVCUBIC_MODE:
  43921. default:
  43922. defines.REFLECTIONMAP_CUBIC = true;
  43923. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  43924. break;
  43925. }
  43926. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  43927. if (reflectionTexture.sphericalPolynomial) {
  43928. defines.USESPHERICALFROMREFLECTIONMAP = true;
  43929. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  43930. defines.USESPHERICALINVERTEX = false;
  43931. }
  43932. else {
  43933. defines.USESPHERICALINVERTEX = true;
  43934. }
  43935. }
  43936. }
  43937. }
  43938. else {
  43939. defines.REFLECTION = false;
  43940. defines.REFLECTIONMAP_3D = false;
  43941. defines.REFLECTIONMAP_SPHERICAL = false;
  43942. defines.REFLECTIONMAP_PLANAR = false;
  43943. defines.REFLECTIONMAP_CUBIC = false;
  43944. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43945. defines.REFLECTIONMAP_PROJECTION = false;
  43946. defines.REFLECTIONMAP_SKYBOX = false;
  43947. defines.REFLECTIONMAP_EXPLICIT = false;
  43948. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43949. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43950. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43951. defines.INVERTCUBICMAP = false;
  43952. defines.USESPHERICALFROMREFLECTIONMAP = false;
  43953. defines.USESPHERICALINVERTEX = false;
  43954. defines.REFLECTIONMAP_OPPOSITEZ = false;
  43955. defines.LODINREFLECTIONALPHA = false;
  43956. defines.GAMMAREFLECTION = false;
  43957. defines.RGBDREFLECTION = false;
  43958. }
  43959. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43960. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43961. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43962. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  43963. }
  43964. else {
  43965. defines.LIGHTMAP = false;
  43966. }
  43967. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43968. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43969. }
  43970. else {
  43971. defines.EMISSIVE = false;
  43972. }
  43973. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43974. if (this._metallicTexture) {
  43975. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  43976. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  43977. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  43978. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  43979. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  43980. }
  43981. else if (this._reflectivityTexture) {
  43982. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  43983. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  43984. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  43985. }
  43986. else {
  43987. defines.REFLECTIVITY = false;
  43988. }
  43989. if (this._microSurfaceTexture) {
  43990. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  43991. }
  43992. else {
  43993. defines.MICROSURFACEMAP = false;
  43994. }
  43995. }
  43996. else {
  43997. defines.REFLECTIVITY = false;
  43998. defines.MICROSURFACEMAP = false;
  43999. }
  44000. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44001. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44002. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44003. defines.PARALLAX = true;
  44004. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44005. }
  44006. else {
  44007. defines.PARALLAX = false;
  44008. }
  44009. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44010. }
  44011. else {
  44012. defines.BUMP = false;
  44013. }
  44014. var refractionTexture = this._getRefractionTexture();
  44015. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44016. defines.REFRACTION = true;
  44017. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44018. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44019. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44020. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44021. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44022. if (this._linkRefractionWithTransparency) {
  44023. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44024. }
  44025. }
  44026. else {
  44027. defines.REFRACTION = false;
  44028. }
  44029. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44030. defines.ENVIRONMENTBRDF = true;
  44031. }
  44032. else {
  44033. defines.ENVIRONMENTBRDF = false;
  44034. }
  44035. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44036. defines.ALPHAFROMALBEDO = true;
  44037. }
  44038. else {
  44039. defines.ALPHAFROMALBEDO = false;
  44040. }
  44041. }
  44042. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44043. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44044. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44045. if (!this.backFaceCulling && this._twoSidedLighting) {
  44046. defines.TWOSIDEDLIGHTING = true;
  44047. }
  44048. else {
  44049. defines.TWOSIDEDLIGHTING = false;
  44050. }
  44051. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44052. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44053. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44054. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44055. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44056. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44057. }
  44058. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44059. this._imageProcessingConfiguration.prepareDefines(defines);
  44060. }
  44061. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44062. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44063. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44064. // Misc.
  44065. if (defines._areMiscDirty) {
  44066. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44067. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44068. }
  44069. // Values that need to be evaluated on every frame
  44070. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44071. // Attribs
  44072. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44073. };
  44074. /**
  44075. * Force shader compilation
  44076. */
  44077. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44078. var _this = this;
  44079. var localOptions = __assign({ clipPlane: false }, options);
  44080. var defines = new PBRMaterialDefines();
  44081. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44082. if (effect.isReady()) {
  44083. if (onCompiled) {
  44084. onCompiled(this);
  44085. }
  44086. }
  44087. else {
  44088. effect.onCompileObservable.add(function () {
  44089. if (onCompiled) {
  44090. onCompiled(_this);
  44091. }
  44092. });
  44093. }
  44094. };
  44095. /**
  44096. * Initializes the uniform buffer layout for the shader.
  44097. */
  44098. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44099. // Order is important !
  44100. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44101. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44102. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44103. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44104. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44105. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44106. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44107. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44108. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44109. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44110. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44111. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44112. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44113. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44114. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44115. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44116. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44117. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44118. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44119. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44120. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44121. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44122. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44123. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44124. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44125. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44126. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44127. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44128. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44129. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44130. this._uniformBuffer.addUniform("pointSize", 1);
  44131. this._uniformBuffer.create();
  44132. };
  44133. /**
  44134. * Unbinds the textures.
  44135. */
  44136. PBRBaseMaterial.prototype.unbind = function () {
  44137. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44138. this._uniformBuffer.setTexture("reflectionSampler", null);
  44139. }
  44140. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44141. this._uniformBuffer.setTexture("refractionSampler", null);
  44142. }
  44143. _super.prototype.unbind.call(this);
  44144. };
  44145. /**
  44146. * Binds the submesh data.
  44147. * @param world - The world matrix.
  44148. * @param mesh - The BJS mesh.
  44149. * @param subMesh - A submesh of the BJS mesh.
  44150. */
  44151. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44152. var scene = this.getScene();
  44153. var defines = subMesh._materialDefines;
  44154. if (!defines) {
  44155. return;
  44156. }
  44157. var effect = subMesh.effect;
  44158. if (!effect) {
  44159. return;
  44160. }
  44161. this._activeEffect = effect;
  44162. // Matrices
  44163. this.bindOnlyWorldMatrix(world);
  44164. // Normal Matrix
  44165. if (defines.OBJECTSPACE_NORMALMAP) {
  44166. world.toNormalMatrix(this._normalMatrix);
  44167. this.bindOnlyNormalMatrix(this._normalMatrix);
  44168. }
  44169. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44170. // Bones
  44171. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44172. var reflectionTexture = null;
  44173. if (mustRebind) {
  44174. this._uniformBuffer.bindToEffect(effect, "Material");
  44175. this.bindViewProjection(effect);
  44176. reflectionTexture = this._getReflectionTexture();
  44177. var refractionTexture = this._getRefractionTexture();
  44178. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44179. // Texture uniforms
  44180. if (scene.texturesEnabled) {
  44181. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44182. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44183. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44184. }
  44185. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44186. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44187. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44188. }
  44189. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44190. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44191. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44192. }
  44193. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44194. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44195. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44196. if (reflectionTexture.boundingBoxSize) {
  44197. var cubeTexture = reflectionTexture;
  44198. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44199. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44200. }
  44201. var polynomials = reflectionTexture.sphericalPolynomial;
  44202. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44203. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44204. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44205. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44206. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44207. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44208. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44209. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44210. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44211. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44212. }
  44213. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44214. }
  44215. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44216. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44217. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44218. }
  44219. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44220. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44221. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44222. }
  44223. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44224. if (this._metallicTexture) {
  44225. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44226. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44227. }
  44228. else if (this._reflectivityTexture) {
  44229. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44230. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44231. }
  44232. if (this._microSurfaceTexture) {
  44233. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44234. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44235. }
  44236. }
  44237. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44238. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44239. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44240. if (scene._mirroredCameraPosition) {
  44241. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44242. }
  44243. else {
  44244. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44245. }
  44246. }
  44247. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44248. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44249. var depth = 1.0;
  44250. if (!refractionTexture.isCube) {
  44251. if (refractionTexture.depth) {
  44252. depth = refractionTexture.depth;
  44253. }
  44254. }
  44255. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44256. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44257. }
  44258. }
  44259. // Point size
  44260. if (this.pointsCloud) {
  44261. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44262. }
  44263. // Colors
  44264. if (defines.METALLICWORKFLOW) {
  44265. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44266. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44267. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44268. }
  44269. else {
  44270. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44271. }
  44272. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44273. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44274. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44275. // Misc
  44276. this._lightingInfos.x = this._directIntensity;
  44277. this._lightingInfos.y = this._emissiveIntensity;
  44278. this._lightingInfos.z = this._environmentIntensity;
  44279. this._lightingInfos.w = this._specularIntensity;
  44280. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44281. }
  44282. // Textures
  44283. if (scene.texturesEnabled) {
  44284. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44285. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44286. }
  44287. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44288. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44289. }
  44290. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44291. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44292. }
  44293. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44294. if (defines.LODBASEDMICROSFURACE) {
  44295. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44296. }
  44297. else {
  44298. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44299. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44300. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44301. }
  44302. }
  44303. if (defines.ENVIRONMENTBRDF) {
  44304. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44305. }
  44306. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44307. if (defines.LODBASEDMICROSFURACE) {
  44308. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44309. }
  44310. else {
  44311. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44312. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44313. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44314. }
  44315. }
  44316. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44317. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44318. }
  44319. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44320. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44321. }
  44322. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44323. if (this._metallicTexture) {
  44324. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44325. }
  44326. else if (this._reflectivityTexture) {
  44327. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44328. }
  44329. if (this._microSurfaceTexture) {
  44330. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44331. }
  44332. }
  44333. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44334. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44335. }
  44336. }
  44337. // Clip plane
  44338. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44339. // Colors
  44340. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44341. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44342. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44343. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44344. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44345. }
  44346. if (mustRebind || !this.isFrozen) {
  44347. // Lights
  44348. if (scene.lightsEnabled && !this._disableLighting) {
  44349. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44350. }
  44351. // View
  44352. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44353. this.bindView(effect);
  44354. }
  44355. // Fog
  44356. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44357. // Morph targets
  44358. if (defines.NUM_MORPH_INFLUENCERS) {
  44359. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44360. }
  44361. // image processing
  44362. this._imageProcessingConfiguration.bind(this._activeEffect);
  44363. // Log. depth
  44364. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44365. }
  44366. this._uniformBuffer.update();
  44367. this._afterBind(mesh, this._activeEffect);
  44368. };
  44369. /**
  44370. * Returns the animatable textures.
  44371. * @returns - Array of animatable textures.
  44372. */
  44373. PBRBaseMaterial.prototype.getAnimatables = function () {
  44374. var results = [];
  44375. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44376. results.push(this._albedoTexture);
  44377. }
  44378. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44379. results.push(this._ambientTexture);
  44380. }
  44381. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44382. results.push(this._opacityTexture);
  44383. }
  44384. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44385. results.push(this._reflectionTexture);
  44386. }
  44387. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44388. results.push(this._emissiveTexture);
  44389. }
  44390. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44391. results.push(this._metallicTexture);
  44392. }
  44393. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44394. results.push(this._reflectivityTexture);
  44395. }
  44396. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44397. results.push(this._bumpTexture);
  44398. }
  44399. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44400. results.push(this._lightmapTexture);
  44401. }
  44402. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44403. results.push(this._refractionTexture);
  44404. }
  44405. return results;
  44406. };
  44407. /**
  44408. * Returns the texture used for reflections.
  44409. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44410. */
  44411. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44412. if (this._reflectionTexture) {
  44413. return this._reflectionTexture;
  44414. }
  44415. return this.getScene().environmentTexture;
  44416. };
  44417. /**
  44418. * Returns the texture used for refraction or null if none is used.
  44419. * @returns - Refection texture if present. If no refraction texture and refraction
  44420. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44421. */
  44422. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44423. if (this._refractionTexture) {
  44424. return this._refractionTexture;
  44425. }
  44426. if (this._linkRefractionWithTransparency) {
  44427. return this.getScene().environmentTexture;
  44428. }
  44429. return null;
  44430. };
  44431. /**
  44432. * Disposes the resources of the material.
  44433. * @param forceDisposeEffect - Forces the disposal of effects.
  44434. * @param forceDisposeTextures - Forces the disposal of all textures.
  44435. */
  44436. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44437. if (forceDisposeTextures) {
  44438. if (this._albedoTexture) {
  44439. this._albedoTexture.dispose();
  44440. }
  44441. if (this._ambientTexture) {
  44442. this._ambientTexture.dispose();
  44443. }
  44444. if (this._opacityTexture) {
  44445. this._opacityTexture.dispose();
  44446. }
  44447. if (this._reflectionTexture) {
  44448. this._reflectionTexture.dispose();
  44449. }
  44450. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44451. this._environmentBRDFTexture.dispose();
  44452. }
  44453. if (this._emissiveTexture) {
  44454. this._emissiveTexture.dispose();
  44455. }
  44456. if (this._metallicTexture) {
  44457. this._metallicTexture.dispose();
  44458. }
  44459. if (this._reflectivityTexture) {
  44460. this._reflectivityTexture.dispose();
  44461. }
  44462. if (this._bumpTexture) {
  44463. this._bumpTexture.dispose();
  44464. }
  44465. if (this._lightmapTexture) {
  44466. this._lightmapTexture.dispose();
  44467. }
  44468. if (this._refractionTexture) {
  44469. this._refractionTexture.dispose();
  44470. }
  44471. }
  44472. this._renderTargets.dispose();
  44473. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44474. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44475. }
  44476. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44477. };
  44478. /**
  44479. * Stores the reflectivity values based on metallic roughness workflow.
  44480. */
  44481. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44482. __decorate([
  44483. BABYLON.serializeAsImageProcessingConfiguration()
  44484. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44485. __decorate([
  44486. BABYLON.serialize()
  44487. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44488. __decorate([
  44489. BABYLON.serialize()
  44490. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44491. return PBRBaseMaterial;
  44492. }(BABYLON.PushMaterial));
  44493. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44494. })(BABYLON || (BABYLON = {}));
  44495. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44496. var BABYLON;
  44497. (function (BABYLON) {
  44498. /**
  44499. * The Physically based simple base material of BJS.
  44500. *
  44501. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44502. * It is used as the base class for both the specGloss and metalRough conventions.
  44503. */
  44504. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44505. __extends(PBRBaseSimpleMaterial, _super);
  44506. /**
  44507. * Instantiates a new PBRMaterial instance.
  44508. *
  44509. * @param name The material name
  44510. * @param scene The scene the material will be use in.
  44511. */
  44512. function PBRBaseSimpleMaterial(name, scene) {
  44513. var _this = _super.call(this, name, scene) || this;
  44514. /**
  44515. * Number of Simultaneous lights allowed on the material.
  44516. */
  44517. _this.maxSimultaneousLights = 4;
  44518. /**
  44519. * If sets to true, disables all the lights affecting the material.
  44520. */
  44521. _this.disableLighting = false;
  44522. /**
  44523. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44524. */
  44525. _this.invertNormalMapX = false;
  44526. /**
  44527. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44528. */
  44529. _this.invertNormalMapY = false;
  44530. /**
  44531. * Emissivie color used to self-illuminate the model.
  44532. */
  44533. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44534. /**
  44535. * Occlusion Channel Strenght.
  44536. */
  44537. _this.occlusionStrength = 1.0;
  44538. _this.useLightmapAsShadowmap = false;
  44539. _this._useAlphaFromAlbedoTexture = true;
  44540. _this._useAmbientInGrayScale = true;
  44541. return _this;
  44542. }
  44543. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44544. /**
  44545. * Gets the current double sided mode.
  44546. */
  44547. get: function () {
  44548. return this._twoSidedLighting;
  44549. },
  44550. /**
  44551. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44552. */
  44553. set: function (value) {
  44554. if (this._twoSidedLighting === value) {
  44555. return;
  44556. }
  44557. this._twoSidedLighting = value;
  44558. this.backFaceCulling = !value;
  44559. this._markAllSubMeshesAsTexturesDirty();
  44560. },
  44561. enumerable: true,
  44562. configurable: true
  44563. });
  44564. /**
  44565. * Return the active textures of the material.
  44566. */
  44567. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44568. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44569. if (this.environmentTexture) {
  44570. activeTextures.push(this.environmentTexture);
  44571. }
  44572. if (this.normalTexture) {
  44573. activeTextures.push(this.normalTexture);
  44574. }
  44575. if (this.emissiveTexture) {
  44576. activeTextures.push(this.emissiveTexture);
  44577. }
  44578. if (this.occlusionTexture) {
  44579. activeTextures.push(this.occlusionTexture);
  44580. }
  44581. if (this.lightmapTexture) {
  44582. activeTextures.push(this.lightmapTexture);
  44583. }
  44584. return activeTextures;
  44585. };
  44586. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44587. if (_super.prototype.hasTexture.call(this, texture)) {
  44588. return true;
  44589. }
  44590. if (this.lightmapTexture === texture) {
  44591. return true;
  44592. }
  44593. return false;
  44594. };
  44595. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44596. return "PBRBaseSimpleMaterial";
  44597. };
  44598. __decorate([
  44599. BABYLON.serialize(),
  44600. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44601. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44602. __decorate([
  44603. BABYLON.serialize(),
  44604. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44605. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44606. __decorate([
  44607. BABYLON.serializeAsTexture(),
  44608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44609. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44610. __decorate([
  44611. BABYLON.serialize(),
  44612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44613. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44614. __decorate([
  44615. BABYLON.serialize(),
  44616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44617. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44618. __decorate([
  44619. BABYLON.serializeAsTexture(),
  44620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44621. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44622. __decorate([
  44623. BABYLON.serializeAsColor3("emissive"),
  44624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44625. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44626. __decorate([
  44627. BABYLON.serializeAsTexture(),
  44628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44629. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44630. __decorate([
  44631. BABYLON.serialize(),
  44632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44633. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44634. __decorate([
  44635. BABYLON.serializeAsTexture(),
  44636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44637. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44638. __decorate([
  44639. BABYLON.serialize(),
  44640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44641. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44642. __decorate([
  44643. BABYLON.serialize()
  44644. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44645. __decorate([
  44646. BABYLON.serializeAsTexture(),
  44647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44648. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44649. __decorate([
  44650. BABYLON.serialize(),
  44651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44652. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44653. return PBRBaseSimpleMaterial;
  44654. }(BABYLON.PBRBaseMaterial));
  44655. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44656. })(BABYLON || (BABYLON = {}));
  44657. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44658. var BABYLON;
  44659. (function (BABYLON) {
  44660. /**
  44661. * The Physically based material of BJS.
  44662. *
  44663. * This offers the main features of a standard PBR material.
  44664. * For more information, please refer to the documentation :
  44665. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44666. */
  44667. var PBRMaterial = /** @class */ (function (_super) {
  44668. __extends(PBRMaterial, _super);
  44669. /**
  44670. * Instantiates a new PBRMaterial instance.
  44671. *
  44672. * @param name The material name
  44673. * @param scene The scene the material will be use in.
  44674. */
  44675. function PBRMaterial(name, scene) {
  44676. var _this = _super.call(this, name, scene) || this;
  44677. /**
  44678. * Intensity of the direct lights e.g. the four lights available in your scene.
  44679. * This impacts both the direct diffuse and specular highlights.
  44680. */
  44681. _this.directIntensity = 1.0;
  44682. /**
  44683. * Intensity of the emissive part of the material.
  44684. * This helps controlling the emissive effect without modifying the emissive color.
  44685. */
  44686. _this.emissiveIntensity = 1.0;
  44687. /**
  44688. * Intensity of the environment e.g. how much the environment will light the object
  44689. * either through harmonics for rough material or through the refelction for shiny ones.
  44690. */
  44691. _this.environmentIntensity = 1.0;
  44692. /**
  44693. * This is a special control allowing the reduction of the specular highlights coming from the
  44694. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44695. */
  44696. _this.specularIntensity = 1.0;
  44697. /**
  44698. * Debug Control allowing disabling the bump map on this material.
  44699. */
  44700. _this.disableBumpMap = false;
  44701. /**
  44702. * AKA Occlusion Texture Intensity in other nomenclature.
  44703. */
  44704. _this.ambientTextureStrength = 1.0;
  44705. /**
  44706. * The color of a material in ambient lighting.
  44707. */
  44708. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44709. /**
  44710. * AKA Diffuse Color in other nomenclature.
  44711. */
  44712. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44713. /**
  44714. * AKA Specular Color in other nomenclature.
  44715. */
  44716. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44717. /**
  44718. * The color reflected from the material.
  44719. */
  44720. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44721. /**
  44722. * The color emitted from the material.
  44723. */
  44724. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44725. /**
  44726. * AKA Glossiness in other nomenclature.
  44727. */
  44728. _this.microSurface = 1.0;
  44729. /**
  44730. * source material index of refraction (IOR)' / 'destination material IOR.
  44731. */
  44732. _this.indexOfRefraction = 0.66;
  44733. /**
  44734. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44735. */
  44736. _this.invertRefractionY = false;
  44737. /**
  44738. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44739. * Materials half opaque for instance using refraction could benefit from this control.
  44740. */
  44741. _this.linkRefractionWithTransparency = false;
  44742. _this.useLightmapAsShadowmap = false;
  44743. /**
  44744. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44745. */
  44746. _this.useAlphaFromAlbedoTexture = false;
  44747. /**
  44748. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44749. */
  44750. _this.forceAlphaTest = false;
  44751. /**
  44752. * Defines the alpha limits in alpha test mode.
  44753. */
  44754. _this.alphaCutOff = 0.4;
  44755. /**
  44756. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44757. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44758. */
  44759. _this.useSpecularOverAlpha = true;
  44760. /**
  44761. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44762. */
  44763. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44764. /**
  44765. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44766. */
  44767. _this.useRoughnessFromMetallicTextureAlpha = true;
  44768. /**
  44769. * Specifies if the metallic texture contains the roughness information in its green channel.
  44770. */
  44771. _this.useRoughnessFromMetallicTextureGreen = false;
  44772. /**
  44773. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44774. */
  44775. _this.useMetallnessFromMetallicTextureBlue = false;
  44776. /**
  44777. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44778. */
  44779. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44780. /**
  44781. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44782. */
  44783. _this.useAmbientInGrayScale = false;
  44784. /**
  44785. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44786. * The material will try to infer what glossiness each pixel should be.
  44787. */
  44788. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44789. /**
  44790. * BJS is using an harcoded light falloff based on a manually sets up range.
  44791. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44792. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44793. */
  44794. _this.usePhysicalLightFalloff = true;
  44795. /**
  44796. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44797. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44798. */
  44799. _this.useRadianceOverAlpha = true;
  44800. /**
  44801. * Allows using an object space normal map (instead of tangent space).
  44802. */
  44803. _this.useObjectSpaceNormalMap = false;
  44804. /**
  44805. * Allows using the bump map in parallax mode.
  44806. */
  44807. _this.useParallax = false;
  44808. /**
  44809. * Allows using the bump map in parallax occlusion mode.
  44810. */
  44811. _this.useParallaxOcclusion = false;
  44812. /**
  44813. * Controls the scale bias of the parallax mode.
  44814. */
  44815. _this.parallaxScaleBias = 0.05;
  44816. /**
  44817. * If sets to true, disables all the lights affecting the material.
  44818. */
  44819. _this.disableLighting = false;
  44820. /**
  44821. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44822. */
  44823. _this.forceIrradianceInFragment = false;
  44824. /**
  44825. * Number of Simultaneous lights allowed on the material.
  44826. */
  44827. _this.maxSimultaneousLights = 4;
  44828. /**
  44829. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44830. */
  44831. _this.invertNormalMapX = false;
  44832. /**
  44833. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44834. */
  44835. _this.invertNormalMapY = false;
  44836. /**
  44837. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44838. */
  44839. _this.twoSidedLighting = false;
  44840. /**
  44841. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44842. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44843. */
  44844. _this.useAlphaFresnel = false;
  44845. /**
  44846. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44847. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44848. */
  44849. _this.useLinearAlphaFresnel = false;
  44850. /**
  44851. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44852. * And/Or occlude the blended part.
  44853. */
  44854. _this.environmentBRDFTexture = null;
  44855. /**
  44856. * Force normal to face away from face.
  44857. */
  44858. _this.forceNormalForward = false;
  44859. /**
  44860. * Enables specular anti aliasing in the PBR shader.
  44861. * It will both interacts on the Geometry for analytical and IBL lighting.
  44862. * It also prefilter the roughness map based on the bump values.
  44863. */
  44864. _this.enableSpecularAntiAliasing = false;
  44865. /**
  44866. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44867. * makes the reflect vector face the model (under horizon).
  44868. */
  44869. _this.useHorizonOcclusion = true;
  44870. /**
  44871. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44872. * too much the area relying on ambient texture to define their ambient occlusion.
  44873. */
  44874. _this.useRadianceOcclusion = true;
  44875. /**
  44876. * If set to true, no lighting calculations will be applied.
  44877. */
  44878. _this.unlit = false;
  44879. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44880. return _this;
  44881. }
  44882. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  44883. /**
  44884. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  44885. */
  44886. get: function () {
  44887. return this._PBRMATERIAL_OPAQUE;
  44888. },
  44889. enumerable: true,
  44890. configurable: true
  44891. });
  44892. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  44893. /**
  44894. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  44895. */
  44896. get: function () {
  44897. return this._PBRMATERIAL_ALPHATEST;
  44898. },
  44899. enumerable: true,
  44900. configurable: true
  44901. });
  44902. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  44903. /**
  44904. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44905. */
  44906. get: function () {
  44907. return this._PBRMATERIAL_ALPHABLEND;
  44908. },
  44909. enumerable: true,
  44910. configurable: true
  44911. });
  44912. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  44913. /**
  44914. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44915. * They are also discarded below the alpha cutoff threshold to improve performances.
  44916. */
  44917. get: function () {
  44918. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  44919. },
  44920. enumerable: true,
  44921. configurable: true
  44922. });
  44923. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  44924. /**
  44925. * Gets the image processing configuration used either in this material.
  44926. */
  44927. get: function () {
  44928. return this._imageProcessingConfiguration;
  44929. },
  44930. /**
  44931. * Sets the Default image processing configuration used either in the this material.
  44932. *
  44933. * If sets to null, the scene one is in use.
  44934. */
  44935. set: function (value) {
  44936. this._attachImageProcessingConfiguration(value);
  44937. // Ensure the effect will be rebuilt.
  44938. this._markAllSubMeshesAsTexturesDirty();
  44939. },
  44940. enumerable: true,
  44941. configurable: true
  44942. });
  44943. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  44944. /**
  44945. * Gets wether the color curves effect is enabled.
  44946. */
  44947. get: function () {
  44948. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44949. },
  44950. /**
  44951. * Sets wether the color curves effect is enabled.
  44952. */
  44953. set: function (value) {
  44954. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  44955. },
  44956. enumerable: true,
  44957. configurable: true
  44958. });
  44959. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  44960. /**
  44961. * Gets wether the color grading effect is enabled.
  44962. */
  44963. get: function () {
  44964. return this.imageProcessingConfiguration.colorGradingEnabled;
  44965. },
  44966. /**
  44967. * Gets wether the color grading effect is enabled.
  44968. */
  44969. set: function (value) {
  44970. this.imageProcessingConfiguration.colorGradingEnabled = value;
  44971. },
  44972. enumerable: true,
  44973. configurable: true
  44974. });
  44975. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  44976. /**
  44977. * Gets wether tonemapping is enabled or not.
  44978. */
  44979. get: function () {
  44980. return this._imageProcessingConfiguration.toneMappingEnabled;
  44981. },
  44982. /**
  44983. * Sets wether tonemapping is enabled or not
  44984. */
  44985. set: function (value) {
  44986. this._imageProcessingConfiguration.toneMappingEnabled = value;
  44987. },
  44988. enumerable: true,
  44989. configurable: true
  44990. });
  44991. ;
  44992. ;
  44993. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  44994. /**
  44995. * The camera exposure used on this material.
  44996. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44997. * This corresponds to a photographic exposure.
  44998. */
  44999. get: function () {
  45000. return this._imageProcessingConfiguration.exposure;
  45001. },
  45002. /**
  45003. * The camera exposure used on this material.
  45004. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45005. * This corresponds to a photographic exposure.
  45006. */
  45007. set: function (value) {
  45008. this._imageProcessingConfiguration.exposure = value;
  45009. },
  45010. enumerable: true,
  45011. configurable: true
  45012. });
  45013. ;
  45014. ;
  45015. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45016. /**
  45017. * Gets The camera contrast used on this material.
  45018. */
  45019. get: function () {
  45020. return this._imageProcessingConfiguration.contrast;
  45021. },
  45022. /**
  45023. * Sets The camera contrast used on this material.
  45024. */
  45025. set: function (value) {
  45026. this._imageProcessingConfiguration.contrast = value;
  45027. },
  45028. enumerable: true,
  45029. configurable: true
  45030. });
  45031. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45032. /**
  45033. * Gets the Color Grading 2D Lookup Texture.
  45034. */
  45035. get: function () {
  45036. return this._imageProcessingConfiguration.colorGradingTexture;
  45037. },
  45038. /**
  45039. * Sets the Color Grading 2D Lookup Texture.
  45040. */
  45041. set: function (value) {
  45042. this._imageProcessingConfiguration.colorGradingTexture = value;
  45043. },
  45044. enumerable: true,
  45045. configurable: true
  45046. });
  45047. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45048. /**
  45049. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45050. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45051. * 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;
  45052. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45053. */
  45054. get: function () {
  45055. return this._imageProcessingConfiguration.colorCurves;
  45056. },
  45057. /**
  45058. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45059. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45060. * 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;
  45061. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45062. */
  45063. set: function (value) {
  45064. this._imageProcessingConfiguration.colorCurves = value;
  45065. },
  45066. enumerable: true,
  45067. configurable: true
  45068. });
  45069. /**
  45070. * Returns the name of this material class.
  45071. */
  45072. PBRMaterial.prototype.getClassName = function () {
  45073. return "PBRMaterial";
  45074. };
  45075. /**
  45076. * Returns an array of the actively used textures.
  45077. * @returns - Array of BaseTextures
  45078. */
  45079. PBRMaterial.prototype.getActiveTextures = function () {
  45080. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45081. if (this._albedoTexture) {
  45082. activeTextures.push(this._albedoTexture);
  45083. }
  45084. if (this._ambientTexture) {
  45085. activeTextures.push(this._ambientTexture);
  45086. }
  45087. if (this._opacityTexture) {
  45088. activeTextures.push(this._opacityTexture);
  45089. }
  45090. if (this._reflectionTexture) {
  45091. activeTextures.push(this._reflectionTexture);
  45092. }
  45093. if (this._emissiveTexture) {
  45094. activeTextures.push(this._emissiveTexture);
  45095. }
  45096. if (this._reflectivityTexture) {
  45097. activeTextures.push(this._reflectivityTexture);
  45098. }
  45099. if (this._metallicTexture) {
  45100. activeTextures.push(this._metallicTexture);
  45101. }
  45102. if (this._microSurfaceTexture) {
  45103. activeTextures.push(this._microSurfaceTexture);
  45104. }
  45105. if (this._bumpTexture) {
  45106. activeTextures.push(this._bumpTexture);
  45107. }
  45108. if (this._lightmapTexture) {
  45109. activeTextures.push(this._lightmapTexture);
  45110. }
  45111. if (this._refractionTexture) {
  45112. activeTextures.push(this._refractionTexture);
  45113. }
  45114. return activeTextures;
  45115. };
  45116. /**
  45117. * Checks to see if a texture is used in the material.
  45118. * @param texture - Base texture to use.
  45119. * @returns - Boolean specifying if a texture is used in the material.
  45120. */
  45121. PBRMaterial.prototype.hasTexture = function (texture) {
  45122. if (_super.prototype.hasTexture.call(this, texture)) {
  45123. return true;
  45124. }
  45125. if (this._albedoTexture === texture) {
  45126. return true;
  45127. }
  45128. if (this._ambientTexture === texture) {
  45129. return true;
  45130. }
  45131. if (this._opacityTexture === texture) {
  45132. return true;
  45133. }
  45134. if (this._reflectionTexture === texture) {
  45135. return true;
  45136. }
  45137. if (this._reflectivityTexture === texture) {
  45138. return true;
  45139. }
  45140. if (this._metallicTexture === texture) {
  45141. return true;
  45142. }
  45143. if (this._microSurfaceTexture === texture) {
  45144. return true;
  45145. }
  45146. if (this._bumpTexture === texture) {
  45147. return true;
  45148. }
  45149. if (this._lightmapTexture === texture) {
  45150. return true;
  45151. }
  45152. if (this._refractionTexture === texture) {
  45153. return true;
  45154. }
  45155. return false;
  45156. };
  45157. /**
  45158. * Makes a duplicate of the current material.
  45159. * @param name - name to use for the new material.
  45160. */
  45161. PBRMaterial.prototype.clone = function (name) {
  45162. var _this = this;
  45163. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45164. clone.id = name;
  45165. clone.name = name;
  45166. return clone;
  45167. };
  45168. /**
  45169. * Serializes this PBR Material.
  45170. * @returns - An object with the serialized material.
  45171. */
  45172. PBRMaterial.prototype.serialize = function () {
  45173. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45174. serializationObject.customType = "BABYLON.PBRMaterial";
  45175. return serializationObject;
  45176. };
  45177. // Statics
  45178. /**
  45179. * Parses a PBR Material from a serialized object.
  45180. * @param source - Serialized object.
  45181. * @param scene - BJS scene instance.
  45182. * @param rootUrl - url for the scene object
  45183. * @returns - PBRMaterial
  45184. */
  45185. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45186. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45187. };
  45188. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45189. /**
  45190. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45191. */
  45192. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45193. /**
  45194. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45195. */
  45196. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45197. /**
  45198. * 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.
  45199. * They are also discarded below the alpha cutoff threshold to improve performances.
  45200. */
  45201. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45202. __decorate([
  45203. BABYLON.serialize(),
  45204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45205. ], PBRMaterial.prototype, "directIntensity", void 0);
  45206. __decorate([
  45207. BABYLON.serialize(),
  45208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45209. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45210. __decorate([
  45211. BABYLON.serialize(),
  45212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45213. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45214. __decorate([
  45215. BABYLON.serialize(),
  45216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45217. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45218. __decorate([
  45219. BABYLON.serialize(),
  45220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45221. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45222. __decorate([
  45223. BABYLON.serializeAsTexture(),
  45224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45225. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45226. __decorate([
  45227. BABYLON.serializeAsTexture(),
  45228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45229. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45230. __decorate([
  45231. BABYLON.serialize(),
  45232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45233. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45234. __decorate([
  45235. BABYLON.serializeAsTexture(),
  45236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45237. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45238. __decorate([
  45239. BABYLON.serializeAsTexture(),
  45240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45241. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45242. __decorate([
  45243. BABYLON.serializeAsTexture(),
  45244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45245. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45246. __decorate([
  45247. BABYLON.serializeAsTexture(),
  45248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45249. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45250. __decorate([
  45251. BABYLON.serializeAsTexture(),
  45252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45253. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45254. __decorate([
  45255. BABYLON.serialize(),
  45256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45257. ], PBRMaterial.prototype, "metallic", void 0);
  45258. __decorate([
  45259. BABYLON.serialize(),
  45260. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45261. ], PBRMaterial.prototype, "roughness", void 0);
  45262. __decorate([
  45263. BABYLON.serializeAsTexture(),
  45264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45265. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45266. __decorate([
  45267. BABYLON.serializeAsTexture(),
  45268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45269. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45270. __decorate([
  45271. BABYLON.serializeAsTexture(),
  45272. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45273. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45274. __decorate([
  45275. BABYLON.serializeAsTexture(),
  45276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45277. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45278. __decorate([
  45279. BABYLON.serializeAsColor3("ambient"),
  45280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45281. ], PBRMaterial.prototype, "ambientColor", void 0);
  45282. __decorate([
  45283. BABYLON.serializeAsColor3("albedo"),
  45284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45285. ], PBRMaterial.prototype, "albedoColor", void 0);
  45286. __decorate([
  45287. BABYLON.serializeAsColor3("reflectivity"),
  45288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45289. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45290. __decorate([
  45291. BABYLON.serializeAsColor3("reflection"),
  45292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45293. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45294. __decorate([
  45295. BABYLON.serializeAsColor3("emissive"),
  45296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45297. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45298. __decorate([
  45299. BABYLON.serialize(),
  45300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45301. ], PBRMaterial.prototype, "microSurface", void 0);
  45302. __decorate([
  45303. BABYLON.serialize(),
  45304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45305. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45306. __decorate([
  45307. BABYLON.serialize(),
  45308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45309. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45310. __decorate([
  45311. BABYLON.serialize(),
  45312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45313. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45314. __decorate([
  45315. BABYLON.serialize(),
  45316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45317. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45318. __decorate([
  45319. BABYLON.serialize(),
  45320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45321. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45322. __decorate([
  45323. BABYLON.serialize(),
  45324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45325. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45326. __decorate([
  45327. BABYLON.serialize(),
  45328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45329. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45330. __decorate([
  45331. BABYLON.serialize(),
  45332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45333. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45334. __decorate([
  45335. BABYLON.serialize(),
  45336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45337. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45338. __decorate([
  45339. BABYLON.serialize(),
  45340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45341. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45342. __decorate([
  45343. BABYLON.serialize(),
  45344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45345. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45346. __decorate([
  45347. BABYLON.serialize(),
  45348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45349. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45350. __decorate([
  45351. BABYLON.serialize(),
  45352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45353. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45354. __decorate([
  45355. BABYLON.serialize(),
  45356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45357. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45358. __decorate([
  45359. BABYLON.serialize(),
  45360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45361. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45362. __decorate([
  45363. BABYLON.serialize(),
  45364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45365. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45366. __decorate([
  45367. BABYLON.serialize(),
  45368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45369. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45370. __decorate([
  45371. BABYLON.serialize(),
  45372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45373. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45374. __decorate([
  45375. BABYLON.serialize(),
  45376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45377. ], PBRMaterial.prototype, "useParallax", void 0);
  45378. __decorate([
  45379. BABYLON.serialize(),
  45380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45381. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45382. __decorate([
  45383. BABYLON.serialize(),
  45384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45385. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45386. __decorate([
  45387. BABYLON.serialize(),
  45388. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45389. ], PBRMaterial.prototype, "disableLighting", void 0);
  45390. __decorate([
  45391. BABYLON.serialize(),
  45392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45393. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45394. __decorate([
  45395. BABYLON.serialize(),
  45396. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45397. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45398. __decorate([
  45399. BABYLON.serialize(),
  45400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45401. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45402. __decorate([
  45403. BABYLON.serialize(),
  45404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45405. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45406. __decorate([
  45407. BABYLON.serialize(),
  45408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45409. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45410. __decorate([
  45411. BABYLON.serialize(),
  45412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45413. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45414. __decorate([
  45415. BABYLON.serialize(),
  45416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45417. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45418. __decorate([
  45419. BABYLON.serializeAsTexture(),
  45420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45421. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45422. __decorate([
  45423. BABYLON.serialize(),
  45424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45425. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45426. __decorate([
  45427. BABYLON.serialize(),
  45428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45429. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45430. __decorate([
  45431. BABYLON.serialize(),
  45432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45433. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45434. __decorate([
  45435. BABYLON.serialize(),
  45436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45437. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45438. __decorate([
  45439. BABYLON.serialize(),
  45440. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45441. ], PBRMaterial.prototype, "unlit", void 0);
  45442. return PBRMaterial;
  45443. }(BABYLON.PBRBaseMaterial));
  45444. BABYLON.PBRMaterial = PBRMaterial;
  45445. })(BABYLON || (BABYLON = {}));
  45446. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45447. var BABYLON;
  45448. (function (BABYLON) {
  45449. /**
  45450. * The PBR material of BJS following the metal roughness convention.
  45451. *
  45452. * This fits to the PBR convention in the GLTF definition:
  45453. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45454. */
  45455. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45456. __extends(PBRMetallicRoughnessMaterial, _super);
  45457. /**
  45458. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45459. *
  45460. * @param name The material name
  45461. * @param scene The scene the material will be use in.
  45462. */
  45463. function PBRMetallicRoughnessMaterial(name, scene) {
  45464. var _this = _super.call(this, name, scene) || this;
  45465. _this._useRoughnessFromMetallicTextureAlpha = false;
  45466. _this._useRoughnessFromMetallicTextureGreen = true;
  45467. _this._useMetallnessFromMetallicTextureBlue = true;
  45468. _this.metallic = 1.0;
  45469. _this.roughness = 1.0;
  45470. return _this;
  45471. }
  45472. /**
  45473. * Return the currrent class name of the material.
  45474. */
  45475. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45476. return "PBRMetallicRoughnessMaterial";
  45477. };
  45478. /**
  45479. * Return the active textures of the material.
  45480. */
  45481. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45482. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45483. if (this.baseTexture) {
  45484. activeTextures.push(this.baseTexture);
  45485. }
  45486. if (this.metallicRoughnessTexture) {
  45487. activeTextures.push(this.metallicRoughnessTexture);
  45488. }
  45489. return activeTextures;
  45490. };
  45491. /**
  45492. * Checks to see if a texture is used in the material.
  45493. * @param texture - Base texture to use.
  45494. * @returns - Boolean specifying if a texture is used in the material.
  45495. */
  45496. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45497. if (_super.prototype.hasTexture.call(this, texture)) {
  45498. return true;
  45499. }
  45500. if (this.baseTexture === texture) {
  45501. return true;
  45502. }
  45503. if (this.metallicRoughnessTexture === texture) {
  45504. return true;
  45505. }
  45506. return false;
  45507. };
  45508. /**
  45509. * Makes a duplicate of the current material.
  45510. * @param name - name to use for the new material.
  45511. */
  45512. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45513. var _this = this;
  45514. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45515. clone.id = name;
  45516. clone.name = name;
  45517. return clone;
  45518. };
  45519. /**
  45520. * Serialize the material to a parsable JSON object.
  45521. */
  45522. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45523. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45524. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45525. return serializationObject;
  45526. };
  45527. /**
  45528. * Parses a JSON object correponding to the serialize function.
  45529. */
  45530. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45531. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45532. };
  45533. __decorate([
  45534. BABYLON.serializeAsColor3(),
  45535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45536. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45537. __decorate([
  45538. BABYLON.serializeAsTexture(),
  45539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45540. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45541. __decorate([
  45542. BABYLON.serialize(),
  45543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45544. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45545. __decorate([
  45546. BABYLON.serialize(),
  45547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45548. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45549. __decorate([
  45550. BABYLON.serializeAsTexture(),
  45551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45552. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45553. return PBRMetallicRoughnessMaterial;
  45554. }(BABYLON.PBRBaseSimpleMaterial));
  45555. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45556. })(BABYLON || (BABYLON = {}));
  45557. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45558. var BABYLON;
  45559. (function (BABYLON) {
  45560. /**
  45561. * The PBR material of BJS following the specular glossiness convention.
  45562. *
  45563. * This fits to the PBR convention in the GLTF definition:
  45564. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45565. */
  45566. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45567. __extends(PBRSpecularGlossinessMaterial, _super);
  45568. /**
  45569. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45570. *
  45571. * @param name The material name
  45572. * @param scene The scene the material will be use in.
  45573. */
  45574. function PBRSpecularGlossinessMaterial(name, scene) {
  45575. var _this = _super.call(this, name, scene) || this;
  45576. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45577. return _this;
  45578. }
  45579. /**
  45580. * Return the currrent class name of the material.
  45581. */
  45582. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45583. return "PBRSpecularGlossinessMaterial";
  45584. };
  45585. /**
  45586. * Return the active textures of the material.
  45587. */
  45588. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45589. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45590. if (this.diffuseTexture) {
  45591. activeTextures.push(this.diffuseTexture);
  45592. }
  45593. if (this.specularGlossinessTexture) {
  45594. activeTextures.push(this.specularGlossinessTexture);
  45595. }
  45596. return activeTextures;
  45597. };
  45598. /**
  45599. * Checks to see if a texture is used in the material.
  45600. * @param texture - Base texture to use.
  45601. * @returns - Boolean specifying if a texture is used in the material.
  45602. */
  45603. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45604. if (_super.prototype.hasTexture.call(this, texture)) {
  45605. return true;
  45606. }
  45607. if (this.diffuseTexture === texture) {
  45608. return true;
  45609. }
  45610. if (this.specularGlossinessTexture === texture) {
  45611. return true;
  45612. }
  45613. return false;
  45614. };
  45615. /**
  45616. * Makes a duplicate of the current material.
  45617. * @param name - name to use for the new material.
  45618. */
  45619. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45620. var _this = this;
  45621. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45622. clone.id = name;
  45623. clone.name = name;
  45624. return clone;
  45625. };
  45626. /**
  45627. * Serialize the material to a parsable JSON object.
  45628. */
  45629. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45630. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45631. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45632. return serializationObject;
  45633. };
  45634. /**
  45635. * Parses a JSON object correponding to the serialize function.
  45636. */
  45637. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45638. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45639. };
  45640. __decorate([
  45641. BABYLON.serializeAsColor3("diffuse"),
  45642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45643. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45644. __decorate([
  45645. BABYLON.serializeAsTexture(),
  45646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45647. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45648. __decorate([
  45649. BABYLON.serializeAsColor3("specular"),
  45650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45651. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45652. __decorate([
  45653. BABYLON.serialize(),
  45654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45655. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45656. __decorate([
  45657. BABYLON.serializeAsTexture(),
  45658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45659. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45660. return PBRSpecularGlossinessMaterial;
  45661. }(BABYLON.PBRBaseSimpleMaterial));
  45662. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45663. })(BABYLON || (BABYLON = {}));
  45664. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45665. var BABYLON;
  45666. (function (BABYLON) {
  45667. BABYLON.CameraInputTypes = {};
  45668. var CameraInputsManager = /** @class */ (function () {
  45669. function CameraInputsManager(camera) {
  45670. this.attached = {};
  45671. this.camera = camera;
  45672. this.checkInputs = function () { };
  45673. }
  45674. /**
  45675. * Add an input method to a camera
  45676. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45677. * @param input camera input method
  45678. */
  45679. CameraInputsManager.prototype.add = function (input) {
  45680. var type = input.getSimpleName();
  45681. if (this.attached[type]) {
  45682. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45683. return;
  45684. }
  45685. this.attached[type] = input;
  45686. input.camera = this.camera;
  45687. //for checkInputs, we are dynamically creating a function
  45688. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45689. if (input.checkInputs) {
  45690. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45691. }
  45692. if (this.attachedElement) {
  45693. input.attachControl(this.attachedElement);
  45694. }
  45695. };
  45696. /**
  45697. * Remove a specific input method from a camera
  45698. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45699. * @param inputToRemove camera input method
  45700. */
  45701. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45702. for (var cam in this.attached) {
  45703. var input = this.attached[cam];
  45704. if (input === inputToRemove) {
  45705. input.detachControl(this.attachedElement);
  45706. input.camera = null;
  45707. delete this.attached[cam];
  45708. this.rebuildInputCheck();
  45709. }
  45710. }
  45711. };
  45712. CameraInputsManager.prototype.removeByType = function (inputType) {
  45713. for (var cam in this.attached) {
  45714. var input = this.attached[cam];
  45715. if (input.getClassName() === inputType) {
  45716. input.detachControl(this.attachedElement);
  45717. input.camera = null;
  45718. delete this.attached[cam];
  45719. this.rebuildInputCheck();
  45720. }
  45721. }
  45722. };
  45723. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45724. var current = this.checkInputs;
  45725. return function () {
  45726. current();
  45727. fn();
  45728. };
  45729. };
  45730. CameraInputsManager.prototype.attachInput = function (input) {
  45731. if (this.attachedElement) {
  45732. input.attachControl(this.attachedElement, this.noPreventDefault);
  45733. }
  45734. };
  45735. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45736. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45737. if (this.attachedElement) {
  45738. return;
  45739. }
  45740. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45741. this.attachedElement = element;
  45742. this.noPreventDefault = noPreventDefault;
  45743. for (var cam in this.attached) {
  45744. this.attached[cam].attachControl(element, noPreventDefault);
  45745. }
  45746. };
  45747. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45748. if (disconnect === void 0) { disconnect = false; }
  45749. if (this.attachedElement !== element) {
  45750. return;
  45751. }
  45752. for (var cam in this.attached) {
  45753. this.attached[cam].detachControl(element);
  45754. if (disconnect) {
  45755. this.attached[cam].camera = null;
  45756. }
  45757. }
  45758. this.attachedElement = null;
  45759. };
  45760. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45761. this.checkInputs = function () { };
  45762. for (var cam in this.attached) {
  45763. var input = this.attached[cam];
  45764. if (input.checkInputs) {
  45765. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45766. }
  45767. }
  45768. };
  45769. /**
  45770. * Remove all attached input methods from a camera
  45771. */
  45772. CameraInputsManager.prototype.clear = function () {
  45773. if (this.attachedElement) {
  45774. this.detachElement(this.attachedElement, true);
  45775. }
  45776. this.attached = {};
  45777. this.attachedElement = null;
  45778. this.checkInputs = function () { };
  45779. };
  45780. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45781. var inputs = {};
  45782. for (var cam in this.attached) {
  45783. var input = this.attached[cam];
  45784. var res = BABYLON.SerializationHelper.Serialize(input);
  45785. inputs[input.getClassName()] = res;
  45786. }
  45787. serializedCamera.inputsmgr = inputs;
  45788. };
  45789. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45790. var parsedInputs = parsedCamera.inputsmgr;
  45791. if (parsedInputs) {
  45792. this.clear();
  45793. for (var n in parsedInputs) {
  45794. var construct = BABYLON.CameraInputTypes[n];
  45795. if (construct) {
  45796. var parsedinput = parsedInputs[n];
  45797. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45798. this.add(input);
  45799. }
  45800. }
  45801. }
  45802. else {
  45803. //2016-03-08 this part is for managing backward compatibility
  45804. for (var n in this.attached) {
  45805. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45806. if (construct) {
  45807. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45808. this.remove(this.attached[n]);
  45809. this.add(input);
  45810. }
  45811. }
  45812. }
  45813. };
  45814. return CameraInputsManager;
  45815. }());
  45816. BABYLON.CameraInputsManager = CameraInputsManager;
  45817. })(BABYLON || (BABYLON = {}));
  45818. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45819. var BABYLON;
  45820. (function (BABYLON) {
  45821. var TargetCamera = /** @class */ (function (_super) {
  45822. __extends(TargetCamera, _super);
  45823. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  45824. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  45825. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  45826. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45827. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45828. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45829. _this.speed = 2.0;
  45830. _this.noRotationConstraint = false;
  45831. _this.lockedTarget = null;
  45832. _this._currentTarget = BABYLON.Vector3.Zero();
  45833. _this._viewMatrix = BABYLON.Matrix.Zero();
  45834. _this._camMatrix = BABYLON.Matrix.Zero();
  45835. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45836. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45837. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45838. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  45839. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45840. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  45841. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  45842. return _this;
  45843. }
  45844. TargetCamera.prototype.getFrontPosition = function (distance) {
  45845. this.getWorldMatrix();
  45846. var direction = this.getTarget().subtract(this.position);
  45847. direction.normalize();
  45848. direction.scaleInPlace(distance);
  45849. return this.globalPosition.add(direction);
  45850. };
  45851. TargetCamera.prototype._getLockedTargetPosition = function () {
  45852. if (!this.lockedTarget) {
  45853. return null;
  45854. }
  45855. if (this.lockedTarget.absolutePosition) {
  45856. this.lockedTarget.computeWorldMatrix();
  45857. }
  45858. return this.lockedTarget.absolutePosition || this.lockedTarget;
  45859. };
  45860. TargetCamera.prototype.storeState = function () {
  45861. this._storedPosition = this.position.clone();
  45862. this._storedRotation = this.rotation.clone();
  45863. if (this.rotationQuaternion) {
  45864. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  45865. }
  45866. return _super.prototype.storeState.call(this);
  45867. };
  45868. /**
  45869. * Restored camera state. You must call storeState() first
  45870. */
  45871. TargetCamera.prototype._restoreStateValues = function () {
  45872. if (!_super.prototype._restoreStateValues.call(this)) {
  45873. return false;
  45874. }
  45875. this.position = this._storedPosition.clone();
  45876. this.rotation = this._storedRotation.clone();
  45877. if (this.rotationQuaternion) {
  45878. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  45879. }
  45880. this.cameraDirection.copyFromFloats(0, 0, 0);
  45881. this.cameraRotation.copyFromFloats(0, 0);
  45882. return true;
  45883. };
  45884. // Cache
  45885. TargetCamera.prototype._initCache = function () {
  45886. _super.prototype._initCache.call(this);
  45887. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45888. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45889. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45890. };
  45891. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  45892. if (!ignoreParentClass) {
  45893. _super.prototype._updateCache.call(this);
  45894. }
  45895. var lockedTargetPosition = this._getLockedTargetPosition();
  45896. if (!lockedTargetPosition) {
  45897. this._cache.lockedTarget = null;
  45898. }
  45899. else {
  45900. if (!this._cache.lockedTarget) {
  45901. this._cache.lockedTarget = lockedTargetPosition.clone();
  45902. }
  45903. else {
  45904. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  45905. }
  45906. }
  45907. this._cache.rotation.copyFrom(this.rotation);
  45908. if (this.rotationQuaternion)
  45909. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45910. };
  45911. // Synchronized
  45912. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  45913. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  45914. return false;
  45915. }
  45916. var lockedTargetPosition = this._getLockedTargetPosition();
  45917. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  45918. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  45919. };
  45920. // Methods
  45921. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  45922. var engine = this.getEngine();
  45923. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  45924. };
  45925. // Target
  45926. TargetCamera.prototype.setTarget = function (target) {
  45927. this.upVector.normalize();
  45928. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  45929. this._camMatrix.invert();
  45930. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  45931. var vDir = target.subtract(this.position);
  45932. if (vDir.x >= 0.0) {
  45933. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  45934. }
  45935. else {
  45936. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  45937. }
  45938. this.rotation.z = 0;
  45939. if (isNaN(this.rotation.x)) {
  45940. this.rotation.x = 0;
  45941. }
  45942. if (isNaN(this.rotation.y)) {
  45943. this.rotation.y = 0;
  45944. }
  45945. if (isNaN(this.rotation.z)) {
  45946. this.rotation.z = 0;
  45947. }
  45948. if (this.rotationQuaternion) {
  45949. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  45950. }
  45951. };
  45952. /**
  45953. * Return the current target position of the camera. This value is expressed in local space.
  45954. */
  45955. TargetCamera.prototype.getTarget = function () {
  45956. return this._currentTarget;
  45957. };
  45958. TargetCamera.prototype._decideIfNeedsToMove = function () {
  45959. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  45960. };
  45961. TargetCamera.prototype._updatePosition = function () {
  45962. if (this.parent) {
  45963. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  45964. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  45965. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  45966. return;
  45967. }
  45968. this.position.addInPlace(this.cameraDirection);
  45969. };
  45970. TargetCamera.prototype._checkInputs = function () {
  45971. var needToMove = this._decideIfNeedsToMove();
  45972. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  45973. // Move
  45974. if (needToMove) {
  45975. this._updatePosition();
  45976. }
  45977. // Rotate
  45978. if (needToRotate) {
  45979. this.rotation.x += this.cameraRotation.x;
  45980. this.rotation.y += this.cameraRotation.y;
  45981. //rotate, if quaternion is set and rotation was used
  45982. if (this.rotationQuaternion) {
  45983. var len = this.rotation.lengthSquared();
  45984. if (len) {
  45985. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  45986. }
  45987. }
  45988. if (!this.noRotationConstraint) {
  45989. var limit = (Math.PI / 2) * 0.95;
  45990. if (this.rotation.x > limit)
  45991. this.rotation.x = limit;
  45992. if (this.rotation.x < -limit)
  45993. this.rotation.x = -limit;
  45994. }
  45995. }
  45996. // Inertia
  45997. if (needToMove) {
  45998. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  45999. this.cameraDirection.x = 0;
  46000. }
  46001. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46002. this.cameraDirection.y = 0;
  46003. }
  46004. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46005. this.cameraDirection.z = 0;
  46006. }
  46007. this.cameraDirection.scaleInPlace(this.inertia);
  46008. }
  46009. if (needToRotate) {
  46010. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46011. this.cameraRotation.x = 0;
  46012. }
  46013. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46014. this.cameraRotation.y = 0;
  46015. }
  46016. this.cameraRotation.scaleInPlace(this.inertia);
  46017. }
  46018. _super.prototype._checkInputs.call(this);
  46019. };
  46020. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46021. if (this.rotationQuaternion) {
  46022. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46023. }
  46024. else {
  46025. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46026. }
  46027. //update the up vector!
  46028. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46029. };
  46030. TargetCamera.prototype._getViewMatrix = function () {
  46031. if (this.lockedTarget) {
  46032. this.setTarget(this._getLockedTargetPosition());
  46033. }
  46034. // Compute
  46035. this._updateCameraRotationMatrix();
  46036. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46037. // Computing target and final matrix
  46038. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46039. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46040. return this._viewMatrix;
  46041. };
  46042. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46043. if (this.parent) {
  46044. var parentWorldMatrix = this.parent.getWorldMatrix();
  46045. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46046. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46047. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46048. this._markSyncedWithParent();
  46049. }
  46050. else {
  46051. this._globalPosition.copyFrom(this.position);
  46052. this._globalCurrentTarget.copyFrom(target);
  46053. this._globalCurrentUpVector.copyFrom(up);
  46054. }
  46055. if (this.getScene().useRightHandedSystem) {
  46056. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46057. }
  46058. else {
  46059. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46060. }
  46061. };
  46062. /**
  46063. * @override
  46064. * Override Camera.createRigCamera
  46065. */
  46066. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46067. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46068. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46069. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46070. if (!this.rotationQuaternion) {
  46071. this.rotationQuaternion = new BABYLON.Quaternion();
  46072. }
  46073. rigCamera._cameraRigParams = {};
  46074. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46075. }
  46076. return rigCamera;
  46077. }
  46078. return null;
  46079. };
  46080. /**
  46081. * @override
  46082. * Override Camera._updateRigCameras
  46083. */
  46084. TargetCamera.prototype._updateRigCameras = function () {
  46085. var camLeft = this._rigCameras[0];
  46086. var camRight = this._rigCameras[1];
  46087. switch (this.cameraRigMode) {
  46088. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46089. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46090. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46091. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46092. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46093. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46094. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46095. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46096. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46097. camLeft.setTarget(this.getTarget());
  46098. camRight.setTarget(this.getTarget());
  46099. break;
  46100. case BABYLON.Camera.RIG_MODE_VR:
  46101. if (camLeft.rotationQuaternion) {
  46102. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46103. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46104. }
  46105. else {
  46106. camLeft.rotation.copyFrom(this.rotation);
  46107. camRight.rotation.copyFrom(this.rotation);
  46108. }
  46109. camLeft.position.copyFrom(this.position);
  46110. camRight.position.copyFrom(this.position);
  46111. break;
  46112. }
  46113. _super.prototype._updateRigCameras.call(this);
  46114. };
  46115. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46116. if (!this._rigCamTransformMatrix) {
  46117. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46118. }
  46119. var target = this.getTarget();
  46120. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46121. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46122. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46123. };
  46124. TargetCamera.prototype.getClassName = function () {
  46125. return "TargetCamera";
  46126. };
  46127. __decorate([
  46128. BABYLON.serializeAsVector3()
  46129. ], TargetCamera.prototype, "rotation", void 0);
  46130. __decorate([
  46131. BABYLON.serialize()
  46132. ], TargetCamera.prototype, "speed", void 0);
  46133. __decorate([
  46134. BABYLON.serializeAsMeshReference("lockedTargetId")
  46135. ], TargetCamera.prototype, "lockedTarget", void 0);
  46136. return TargetCamera;
  46137. }(BABYLON.Camera));
  46138. BABYLON.TargetCamera = TargetCamera;
  46139. })(BABYLON || (BABYLON = {}));
  46140. //# sourceMappingURL=babylon.targetCamera.js.map
  46141. var BABYLON;
  46142. (function (BABYLON) {
  46143. var FreeCameraMouseInput = /** @class */ (function () {
  46144. function FreeCameraMouseInput(touchEnabled) {
  46145. if (touchEnabled === void 0) { touchEnabled = true; }
  46146. this.touchEnabled = touchEnabled;
  46147. this.buttons = [0, 1, 2];
  46148. this.angularSensibility = 2000.0;
  46149. this.previousPosition = null;
  46150. }
  46151. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46152. var _this = this;
  46153. var engine = this.camera.getEngine();
  46154. if (!this._pointerInput) {
  46155. this._pointerInput = function (p, s) {
  46156. var evt = p.event;
  46157. if (engine.isInVRExclusivePointerMode) {
  46158. return;
  46159. }
  46160. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46161. return;
  46162. }
  46163. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46164. return;
  46165. }
  46166. var srcElement = (evt.srcElement || evt.target);
  46167. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46168. try {
  46169. srcElement.setPointerCapture(evt.pointerId);
  46170. }
  46171. catch (e) {
  46172. //Nothing to do with the error. Execution will continue.
  46173. }
  46174. _this.previousPosition = {
  46175. x: evt.clientX,
  46176. y: evt.clientY
  46177. };
  46178. if (!noPreventDefault) {
  46179. evt.preventDefault();
  46180. element.focus();
  46181. }
  46182. }
  46183. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46184. try {
  46185. srcElement.releasePointerCapture(evt.pointerId);
  46186. }
  46187. catch (e) {
  46188. //Nothing to do with the error.
  46189. }
  46190. _this.previousPosition = null;
  46191. if (!noPreventDefault) {
  46192. evt.preventDefault();
  46193. }
  46194. }
  46195. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46196. if (!_this.previousPosition || engine.isPointerLock) {
  46197. return;
  46198. }
  46199. var offsetX = evt.clientX - _this.previousPosition.x;
  46200. if (_this.camera.getScene().useRightHandedSystem)
  46201. offsetX *= -1;
  46202. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46203. offsetX *= -1;
  46204. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46205. var offsetY = evt.clientY - _this.previousPosition.y;
  46206. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46207. _this.previousPosition = {
  46208. x: evt.clientX,
  46209. y: evt.clientY
  46210. };
  46211. if (!noPreventDefault) {
  46212. evt.preventDefault();
  46213. }
  46214. }
  46215. };
  46216. }
  46217. this._onMouseMove = function (evt) {
  46218. if (!engine.isPointerLock) {
  46219. return;
  46220. }
  46221. if (engine.isInVRExclusivePointerMode) {
  46222. return;
  46223. }
  46224. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46225. if (_this.camera.getScene().useRightHandedSystem)
  46226. offsetX *= -1;
  46227. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46228. offsetX *= -1;
  46229. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46230. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46231. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46232. _this.previousPosition = null;
  46233. if (!noPreventDefault) {
  46234. evt.preventDefault();
  46235. }
  46236. };
  46237. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46238. element.addEventListener("mousemove", this._onMouseMove, false);
  46239. };
  46240. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46241. if (this._observer && element) {
  46242. this.camera.getScene().onPointerObservable.remove(this._observer);
  46243. if (this._onMouseMove) {
  46244. element.removeEventListener("mousemove", this._onMouseMove);
  46245. }
  46246. this._observer = null;
  46247. this._onMouseMove = null;
  46248. this.previousPosition = null;
  46249. }
  46250. };
  46251. FreeCameraMouseInput.prototype.getClassName = function () {
  46252. return "FreeCameraMouseInput";
  46253. };
  46254. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46255. return "mouse";
  46256. };
  46257. __decorate([
  46258. BABYLON.serialize()
  46259. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46260. __decorate([
  46261. BABYLON.serialize()
  46262. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46263. return FreeCameraMouseInput;
  46264. }());
  46265. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46266. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46267. })(BABYLON || (BABYLON = {}));
  46268. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46269. var BABYLON;
  46270. (function (BABYLON) {
  46271. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46272. function FreeCameraKeyboardMoveInput() {
  46273. this._keys = new Array();
  46274. this.keysUp = [38];
  46275. this.keysDown = [40];
  46276. this.keysLeft = [37];
  46277. this.keysRight = [39];
  46278. }
  46279. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46280. var _this = this;
  46281. if (this._onCanvasBlurObserver) {
  46282. return;
  46283. }
  46284. this._scene = this.camera.getScene();
  46285. this._engine = this._scene.getEngine();
  46286. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46287. _this._keys = [];
  46288. });
  46289. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46290. var evt = info.event;
  46291. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46292. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46293. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46294. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46295. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46296. var index = _this._keys.indexOf(evt.keyCode);
  46297. if (index === -1) {
  46298. _this._keys.push(evt.keyCode);
  46299. }
  46300. if (!noPreventDefault) {
  46301. evt.preventDefault();
  46302. }
  46303. }
  46304. }
  46305. else {
  46306. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46307. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46308. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46309. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46310. var index = _this._keys.indexOf(evt.keyCode);
  46311. if (index >= 0) {
  46312. _this._keys.splice(index, 1);
  46313. }
  46314. if (!noPreventDefault) {
  46315. evt.preventDefault();
  46316. }
  46317. }
  46318. }
  46319. });
  46320. };
  46321. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46322. if (this._scene) {
  46323. if (this._onKeyboardObserver) {
  46324. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46325. }
  46326. if (this._onCanvasBlurObserver) {
  46327. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46328. }
  46329. this._onKeyboardObserver = null;
  46330. this._onCanvasBlurObserver = null;
  46331. }
  46332. this._keys = [];
  46333. };
  46334. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46335. if (this._onKeyboardObserver) {
  46336. var camera = this.camera;
  46337. // Keyboard
  46338. for (var index = 0; index < this._keys.length; index++) {
  46339. var keyCode = this._keys[index];
  46340. var speed = camera._computeLocalCameraSpeed();
  46341. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46342. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46343. }
  46344. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46345. camera._localDirection.copyFromFloats(0, 0, speed);
  46346. }
  46347. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46348. camera._localDirection.copyFromFloats(speed, 0, 0);
  46349. }
  46350. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46351. camera._localDirection.copyFromFloats(0, 0, -speed);
  46352. }
  46353. if (camera.getScene().useRightHandedSystem) {
  46354. camera._localDirection.z *= -1;
  46355. }
  46356. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46357. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46358. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46359. }
  46360. }
  46361. };
  46362. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46363. return "FreeCameraKeyboardMoveInput";
  46364. };
  46365. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46366. this._keys = [];
  46367. };
  46368. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46369. return "keyboard";
  46370. };
  46371. __decorate([
  46372. BABYLON.serialize()
  46373. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46374. __decorate([
  46375. BABYLON.serialize()
  46376. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46377. __decorate([
  46378. BABYLON.serialize()
  46379. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46380. __decorate([
  46381. BABYLON.serialize()
  46382. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46383. return FreeCameraKeyboardMoveInput;
  46384. }());
  46385. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46386. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46387. })(BABYLON || (BABYLON = {}));
  46388. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46389. var BABYLON;
  46390. (function (BABYLON) {
  46391. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46392. __extends(FreeCameraInputsManager, _super);
  46393. function FreeCameraInputsManager(camera) {
  46394. return _super.call(this, camera) || this;
  46395. }
  46396. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46397. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46398. return this;
  46399. };
  46400. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46401. if (touchEnabled === void 0) { touchEnabled = true; }
  46402. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46403. return this;
  46404. };
  46405. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46406. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46407. return this;
  46408. };
  46409. FreeCameraInputsManager.prototype.addTouch = function () {
  46410. this.add(new BABYLON.FreeCameraTouchInput());
  46411. return this;
  46412. };
  46413. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46414. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46415. return this;
  46416. };
  46417. return FreeCameraInputsManager;
  46418. }(BABYLON.CameraInputsManager));
  46419. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46420. })(BABYLON || (BABYLON = {}));
  46421. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46422. var BABYLON;
  46423. (function (BABYLON) {
  46424. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46425. // Forcing to use the Universal camera
  46426. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46427. });
  46428. var FreeCamera = /** @class */ (function (_super) {
  46429. __extends(FreeCamera, _super);
  46430. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46431. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46432. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46433. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46434. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46435. _this.checkCollisions = false;
  46436. _this.applyGravity = false;
  46437. _this._needMoveForGravity = false;
  46438. _this._oldPosition = BABYLON.Vector3.Zero();
  46439. _this._diffPosition = BABYLON.Vector3.Zero();
  46440. _this._newPosition = BABYLON.Vector3.Zero();
  46441. // Collisions
  46442. _this._collisionMask = -1;
  46443. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46444. if (collidedMesh === void 0) { collidedMesh = null; }
  46445. //TODO move this to the collision coordinator!
  46446. if (_this.getScene().workerCollisions)
  46447. newPosition.multiplyInPlace(_this._collider._radius);
  46448. var updatePosition = function (newPos) {
  46449. _this._newPosition.copyFrom(newPos);
  46450. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46451. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46452. _this.position.addInPlace(_this._diffPosition);
  46453. if (_this.onCollide && collidedMesh) {
  46454. _this.onCollide(collidedMesh);
  46455. }
  46456. }
  46457. };
  46458. updatePosition(newPosition);
  46459. };
  46460. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46461. _this.inputs.addKeyboard().addMouse();
  46462. return _this;
  46463. }
  46464. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46465. //-- begin properties for backward compatibility for inputs
  46466. /**
  46467. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46468. * Higher values reduce sensitivity.
  46469. */
  46470. get: function () {
  46471. var mouse = this.inputs.attached["mouse"];
  46472. if (mouse)
  46473. return mouse.angularSensibility;
  46474. return 0;
  46475. },
  46476. /**
  46477. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46478. * Higher values reduce sensitivity.
  46479. */
  46480. set: function (value) {
  46481. var mouse = this.inputs.attached["mouse"];
  46482. if (mouse)
  46483. mouse.angularSensibility = value;
  46484. },
  46485. enumerable: true,
  46486. configurable: true
  46487. });
  46488. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46489. get: function () {
  46490. var keyboard = this.inputs.attached["keyboard"];
  46491. if (keyboard)
  46492. return keyboard.keysUp;
  46493. return [];
  46494. },
  46495. set: function (value) {
  46496. var keyboard = this.inputs.attached["keyboard"];
  46497. if (keyboard)
  46498. keyboard.keysUp = value;
  46499. },
  46500. enumerable: true,
  46501. configurable: true
  46502. });
  46503. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46504. get: function () {
  46505. var keyboard = this.inputs.attached["keyboard"];
  46506. if (keyboard)
  46507. return keyboard.keysDown;
  46508. return [];
  46509. },
  46510. set: function (value) {
  46511. var keyboard = this.inputs.attached["keyboard"];
  46512. if (keyboard)
  46513. keyboard.keysDown = value;
  46514. },
  46515. enumerable: true,
  46516. configurable: true
  46517. });
  46518. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46519. get: function () {
  46520. var keyboard = this.inputs.attached["keyboard"];
  46521. if (keyboard)
  46522. return keyboard.keysLeft;
  46523. return [];
  46524. },
  46525. set: function (value) {
  46526. var keyboard = this.inputs.attached["keyboard"];
  46527. if (keyboard)
  46528. keyboard.keysLeft = value;
  46529. },
  46530. enumerable: true,
  46531. configurable: true
  46532. });
  46533. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46534. get: function () {
  46535. var keyboard = this.inputs.attached["keyboard"];
  46536. if (keyboard)
  46537. return keyboard.keysRight;
  46538. return [];
  46539. },
  46540. set: function (value) {
  46541. var keyboard = this.inputs.attached["keyboard"];
  46542. if (keyboard)
  46543. keyboard.keysRight = value;
  46544. },
  46545. enumerable: true,
  46546. configurable: true
  46547. });
  46548. // Controls
  46549. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46550. this.inputs.attachElement(element, noPreventDefault);
  46551. };
  46552. FreeCamera.prototype.detachControl = function (element) {
  46553. this.inputs.detachElement(element);
  46554. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46555. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46556. };
  46557. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46558. get: function () {
  46559. return this._collisionMask;
  46560. },
  46561. set: function (mask) {
  46562. this._collisionMask = !isNaN(mask) ? mask : -1;
  46563. },
  46564. enumerable: true,
  46565. configurable: true
  46566. });
  46567. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46568. var globalPosition;
  46569. if (this.parent) {
  46570. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46571. }
  46572. else {
  46573. globalPosition = this.position;
  46574. }
  46575. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46576. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46577. if (!this._collider) {
  46578. this._collider = new BABYLON.Collider();
  46579. }
  46580. this._collider._radius = this.ellipsoid;
  46581. this._collider.collisionMask = this._collisionMask;
  46582. //no need for clone, as long as gravity is not on.
  46583. var actualDisplacement = displacement;
  46584. //add gravity to the direction to prevent the dual-collision checking
  46585. if (this.applyGravity) {
  46586. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46587. actualDisplacement = displacement.add(this.getScene().gravity);
  46588. }
  46589. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46590. };
  46591. FreeCamera.prototype._checkInputs = function () {
  46592. if (!this._localDirection) {
  46593. this._localDirection = BABYLON.Vector3.Zero();
  46594. this._transformedDirection = BABYLON.Vector3.Zero();
  46595. }
  46596. this.inputs.checkInputs();
  46597. _super.prototype._checkInputs.call(this);
  46598. };
  46599. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46600. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46601. };
  46602. FreeCamera.prototype._updatePosition = function () {
  46603. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46604. this._collideWithWorld(this.cameraDirection);
  46605. }
  46606. else {
  46607. _super.prototype._updatePosition.call(this);
  46608. }
  46609. };
  46610. FreeCamera.prototype.dispose = function () {
  46611. this.inputs.clear();
  46612. _super.prototype.dispose.call(this);
  46613. };
  46614. FreeCamera.prototype.getClassName = function () {
  46615. return "FreeCamera";
  46616. };
  46617. __decorate([
  46618. BABYLON.serializeAsVector3()
  46619. ], FreeCamera.prototype, "ellipsoid", void 0);
  46620. __decorate([
  46621. BABYLON.serializeAsVector3()
  46622. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46623. __decorate([
  46624. BABYLON.serialize()
  46625. ], FreeCamera.prototype, "checkCollisions", void 0);
  46626. __decorate([
  46627. BABYLON.serialize()
  46628. ], FreeCamera.prototype, "applyGravity", void 0);
  46629. return FreeCamera;
  46630. }(BABYLON.TargetCamera));
  46631. BABYLON.FreeCamera = FreeCamera;
  46632. })(BABYLON || (BABYLON = {}));
  46633. //# sourceMappingURL=babylon.freeCamera.js.map
  46634. var BABYLON;
  46635. (function (BABYLON) {
  46636. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46637. function ArcRotateCameraKeyboardMoveInput() {
  46638. this._keys = new Array();
  46639. this.keysUp = [38];
  46640. this.keysDown = [40];
  46641. this.keysLeft = [37];
  46642. this.keysRight = [39];
  46643. this.keysReset = [220];
  46644. this.panningSensibility = 50.0;
  46645. this.zoomingSensibility = 25.0;
  46646. this.useAltToZoom = true;
  46647. }
  46648. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46649. var _this = this;
  46650. if (this._onCanvasBlurObserver) {
  46651. return;
  46652. }
  46653. this._scene = this.camera.getScene();
  46654. this._engine = this._scene.getEngine();
  46655. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46656. _this._keys = [];
  46657. });
  46658. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46659. var evt = info.event;
  46660. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46661. _this._ctrlPressed = evt.ctrlKey;
  46662. _this._altPressed = evt.altKey;
  46663. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46664. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46665. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46666. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46667. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46668. var index = _this._keys.indexOf(evt.keyCode);
  46669. if (index === -1) {
  46670. _this._keys.push(evt.keyCode);
  46671. }
  46672. if (evt.preventDefault) {
  46673. if (!noPreventDefault) {
  46674. evt.preventDefault();
  46675. }
  46676. }
  46677. }
  46678. }
  46679. else {
  46680. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46681. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46682. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46683. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46684. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46685. var index = _this._keys.indexOf(evt.keyCode);
  46686. if (index >= 0) {
  46687. _this._keys.splice(index, 1);
  46688. }
  46689. if (evt.preventDefault) {
  46690. if (!noPreventDefault) {
  46691. evt.preventDefault();
  46692. }
  46693. }
  46694. }
  46695. }
  46696. });
  46697. };
  46698. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46699. if (this._scene) {
  46700. if (this._onKeyboardObserver) {
  46701. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46702. }
  46703. if (this._onCanvasBlurObserver) {
  46704. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46705. }
  46706. this._onKeyboardObserver = null;
  46707. this._onCanvasBlurObserver = null;
  46708. }
  46709. this._keys = [];
  46710. };
  46711. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46712. if (this._onKeyboardObserver) {
  46713. var camera = this.camera;
  46714. for (var index = 0; index < this._keys.length; index++) {
  46715. var keyCode = this._keys[index];
  46716. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46717. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46718. camera.inertialPanningX -= 1 / this.panningSensibility;
  46719. }
  46720. else {
  46721. camera.inertialAlphaOffset -= 0.01;
  46722. }
  46723. }
  46724. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46725. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46726. camera.inertialPanningY += 1 / this.panningSensibility;
  46727. }
  46728. else if (this._altPressed && this.useAltToZoom) {
  46729. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46730. }
  46731. else {
  46732. camera.inertialBetaOffset -= 0.01;
  46733. }
  46734. }
  46735. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46736. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46737. camera.inertialPanningX += 1 / this.panningSensibility;
  46738. }
  46739. else {
  46740. camera.inertialAlphaOffset += 0.01;
  46741. }
  46742. }
  46743. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46744. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46745. camera.inertialPanningY -= 1 / this.panningSensibility;
  46746. }
  46747. else if (this._altPressed && this.useAltToZoom) {
  46748. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46749. }
  46750. else {
  46751. camera.inertialBetaOffset += 0.01;
  46752. }
  46753. }
  46754. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46755. camera.restoreState();
  46756. }
  46757. }
  46758. }
  46759. };
  46760. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46761. return "ArcRotateCameraKeyboardMoveInput";
  46762. };
  46763. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46764. return "keyboard";
  46765. };
  46766. __decorate([
  46767. BABYLON.serialize()
  46768. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46769. __decorate([
  46770. BABYLON.serialize()
  46771. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46772. __decorate([
  46773. BABYLON.serialize()
  46774. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46775. __decorate([
  46776. BABYLON.serialize()
  46777. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46778. __decorate([
  46779. BABYLON.serialize()
  46780. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46781. __decorate([
  46782. BABYLON.serialize()
  46783. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46784. __decorate([
  46785. BABYLON.serialize()
  46786. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46787. __decorate([
  46788. BABYLON.serialize()
  46789. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46790. return ArcRotateCameraKeyboardMoveInput;
  46791. }());
  46792. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46793. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46794. })(BABYLON || (BABYLON = {}));
  46795. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46796. var BABYLON;
  46797. (function (BABYLON) {
  46798. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46799. function ArcRotateCameraMouseWheelInput() {
  46800. this.wheelPrecision = 3.0;
  46801. /**
  46802. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46803. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46804. */
  46805. this.wheelDeltaPercentage = 0;
  46806. }
  46807. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46808. var _this = this;
  46809. this._wheel = function (p, s) {
  46810. //sanity check - this should be a PointerWheel event.
  46811. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46812. return;
  46813. var event = p.event;
  46814. var delta = 0;
  46815. if (event.wheelDelta) {
  46816. if (_this.wheelDeltaPercentage) {
  46817. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46818. if (event.wheelDelta > 0) {
  46819. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46820. }
  46821. else {
  46822. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46823. }
  46824. }
  46825. else {
  46826. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46827. }
  46828. }
  46829. else if (event.detail) {
  46830. delta = -event.detail / _this.wheelPrecision;
  46831. }
  46832. if (delta)
  46833. _this.camera.inertialRadiusOffset += delta;
  46834. if (event.preventDefault) {
  46835. if (!noPreventDefault) {
  46836. event.preventDefault();
  46837. }
  46838. }
  46839. };
  46840. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46841. };
  46842. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46843. if (this._observer && element) {
  46844. this.camera.getScene().onPointerObservable.remove(this._observer);
  46845. this._observer = null;
  46846. this._wheel = null;
  46847. }
  46848. };
  46849. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46850. return "ArcRotateCameraMouseWheelInput";
  46851. };
  46852. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  46853. return "mousewheel";
  46854. };
  46855. __decorate([
  46856. BABYLON.serialize()
  46857. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  46858. __decorate([
  46859. BABYLON.serialize()
  46860. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  46861. return ArcRotateCameraMouseWheelInput;
  46862. }());
  46863. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  46864. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  46865. })(BABYLON || (BABYLON = {}));
  46866. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  46867. var BABYLON;
  46868. (function (BABYLON) {
  46869. var ArcRotateCameraPointersInput = /** @class */ (function () {
  46870. function ArcRotateCameraPointersInput() {
  46871. this.buttons = [0, 1, 2];
  46872. this.angularSensibilityX = 1000.0;
  46873. this.angularSensibilityY = 1000.0;
  46874. this.pinchPrecision = 12.0;
  46875. /**
  46876. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  46877. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  46878. */
  46879. this.pinchDeltaPercentage = 0;
  46880. this.panningSensibility = 1000.0;
  46881. this.multiTouchPanning = true;
  46882. this.multiTouchPanAndZoom = true;
  46883. this._isPanClick = false;
  46884. this.pinchInwards = true;
  46885. }
  46886. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  46887. var _this = this;
  46888. var engine = this.camera.getEngine();
  46889. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  46890. var pointA = null;
  46891. var pointB = null;
  46892. var previousPinchSquaredDistance = 0;
  46893. var initialDistance = 0;
  46894. var twoFingerActivityCount = 0;
  46895. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  46896. this._pointerInput = function (p, s) {
  46897. var evt = p.event;
  46898. var isTouch = p.event.pointerType === "touch";
  46899. if (engine.isInVRExclusivePointerMode) {
  46900. return;
  46901. }
  46902. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46903. return;
  46904. }
  46905. var srcElement = (evt.srcElement || evt.target);
  46906. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46907. try {
  46908. srcElement.setPointerCapture(evt.pointerId);
  46909. }
  46910. catch (e) {
  46911. //Nothing to do with the error. Execution will continue.
  46912. }
  46913. // Manage panning with pan button click
  46914. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  46915. // manage pointers
  46916. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  46917. if (pointA === null) {
  46918. pointA = cacheSoloPointer;
  46919. }
  46920. else if (pointB === null) {
  46921. pointB = cacheSoloPointer;
  46922. }
  46923. if (!noPreventDefault) {
  46924. evt.preventDefault();
  46925. element.focus();
  46926. }
  46927. }
  46928. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  46929. _this.camera.restoreState();
  46930. }
  46931. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46932. try {
  46933. srcElement.releasePointerCapture(evt.pointerId);
  46934. }
  46935. catch (e) {
  46936. //Nothing to do with the error.
  46937. }
  46938. cacheSoloPointer = null;
  46939. previousPinchSquaredDistance = 0;
  46940. previousMultiTouchPanPosition.isPaning = false;
  46941. previousMultiTouchPanPosition.isPinching = false;
  46942. twoFingerActivityCount = 0;
  46943. initialDistance = 0;
  46944. if (!isTouch) {
  46945. pointB = null; // Mouse and pen are mono pointer
  46946. }
  46947. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  46948. //but emptying completly pointers collection is required to fix a bug on iPhone :
  46949. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  46950. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  46951. if (engine._badOS) {
  46952. pointA = pointB = null;
  46953. }
  46954. else {
  46955. //only remove the impacted pointer in case of multitouch allowing on most
  46956. //platforms switching from rotate to zoom and pan seamlessly.
  46957. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  46958. pointA = pointB;
  46959. pointB = null;
  46960. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  46961. }
  46962. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  46963. pointB = null;
  46964. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  46965. }
  46966. else {
  46967. pointA = pointB = null;
  46968. }
  46969. }
  46970. if (!noPreventDefault) {
  46971. evt.preventDefault();
  46972. }
  46973. }
  46974. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46975. if (!noPreventDefault) {
  46976. evt.preventDefault();
  46977. }
  46978. // One button down
  46979. if (pointA && pointB === null && cacheSoloPointer) {
  46980. if (_this.panningSensibility !== 0 &&
  46981. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  46982. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  46983. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  46984. }
  46985. else {
  46986. var offsetX = evt.clientX - cacheSoloPointer.x;
  46987. var offsetY = evt.clientY - cacheSoloPointer.y;
  46988. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  46989. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  46990. }
  46991. cacheSoloPointer.x = evt.clientX;
  46992. cacheSoloPointer.y = evt.clientY;
  46993. }
  46994. // Two buttons down: pinch/pan
  46995. else if (pointA && pointB) {
  46996. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  46997. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  46998. ed.x = evt.clientX;
  46999. ed.y = evt.clientY;
  47000. var direction = _this.pinchInwards ? 1 : -1;
  47001. var distX = pointA.x - pointB.x;
  47002. var distY = pointA.y - pointB.y;
  47003. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47004. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47005. if (previousPinchSquaredDistance === 0) {
  47006. initialDistance = pinchDistance;
  47007. previousPinchSquaredDistance = pinchSquaredDistance;
  47008. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47009. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47010. return;
  47011. }
  47012. if (_this.multiTouchPanAndZoom) {
  47013. if (_this.pinchDeltaPercentage) {
  47014. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47015. }
  47016. else {
  47017. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47018. (_this.pinchPrecision *
  47019. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47020. direction);
  47021. }
  47022. if (_this.panningSensibility !== 0) {
  47023. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47024. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47025. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47026. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47027. previousMultiTouchPanPosition.x = pointersCenterX;
  47028. previousMultiTouchPanPosition.y = pointersCenterY;
  47029. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47030. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47031. }
  47032. }
  47033. else {
  47034. twoFingerActivityCount++;
  47035. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47036. if (_this.pinchDeltaPercentage) {
  47037. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47038. }
  47039. else {
  47040. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47041. (_this.pinchPrecision *
  47042. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47043. direction);
  47044. }
  47045. previousMultiTouchPanPosition.isPaning = false;
  47046. previousMultiTouchPanPosition.isPinching = true;
  47047. }
  47048. else {
  47049. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47050. if (!previousMultiTouchPanPosition.isPaning) {
  47051. previousMultiTouchPanPosition.isPaning = true;
  47052. previousMultiTouchPanPosition.isPinching = false;
  47053. previousMultiTouchPanPosition.x = ed.x;
  47054. previousMultiTouchPanPosition.y = ed.y;
  47055. return;
  47056. }
  47057. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47058. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47059. }
  47060. }
  47061. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47062. previousMultiTouchPanPosition.x = ed.x;
  47063. previousMultiTouchPanPosition.y = ed.y;
  47064. }
  47065. }
  47066. previousPinchSquaredDistance = pinchSquaredDistance;
  47067. }
  47068. }
  47069. };
  47070. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47071. this._onContextMenu = function (evt) {
  47072. evt.preventDefault();
  47073. };
  47074. if (!this.camera._useCtrlForPanning) {
  47075. element.addEventListener("contextmenu", this._onContextMenu, false);
  47076. }
  47077. this._onLostFocus = function () {
  47078. //this._keys = [];
  47079. pointA = pointB = null;
  47080. previousPinchSquaredDistance = 0;
  47081. previousMultiTouchPanPosition.isPaning = false;
  47082. previousMultiTouchPanPosition.isPinching = false;
  47083. twoFingerActivityCount = 0;
  47084. cacheSoloPointer = null;
  47085. initialDistance = 0;
  47086. };
  47087. this._onMouseMove = function (evt) {
  47088. if (!engine.isPointerLock) {
  47089. return;
  47090. }
  47091. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47092. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47093. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47094. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47095. if (!noPreventDefault) {
  47096. evt.preventDefault();
  47097. }
  47098. };
  47099. this._onGestureStart = function (e) {
  47100. if (window.MSGesture === undefined) {
  47101. return;
  47102. }
  47103. if (!_this._MSGestureHandler) {
  47104. _this._MSGestureHandler = new MSGesture();
  47105. _this._MSGestureHandler.target = element;
  47106. }
  47107. _this._MSGestureHandler.addPointer(e.pointerId);
  47108. };
  47109. this._onGesture = function (e) {
  47110. _this.camera.radius *= e.scale;
  47111. if (e.preventDefault) {
  47112. if (!noPreventDefault) {
  47113. e.stopPropagation();
  47114. e.preventDefault();
  47115. }
  47116. }
  47117. };
  47118. element.addEventListener("mousemove", this._onMouseMove, false);
  47119. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47120. element.addEventListener("MSGestureChange", this._onGesture, false);
  47121. BABYLON.Tools.RegisterTopRootEvents([
  47122. { name: "blur", handler: this._onLostFocus }
  47123. ]);
  47124. };
  47125. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47126. if (this._onLostFocus) {
  47127. BABYLON.Tools.UnregisterTopRootEvents([
  47128. { name: "blur", handler: this._onLostFocus }
  47129. ]);
  47130. }
  47131. if (element && this._observer) {
  47132. this.camera.getScene().onPointerObservable.remove(this._observer);
  47133. this._observer = null;
  47134. if (this._onContextMenu) {
  47135. element.removeEventListener("contextmenu", this._onContextMenu);
  47136. }
  47137. if (this._onMouseMove) {
  47138. element.removeEventListener("mousemove", this._onMouseMove);
  47139. }
  47140. if (this._onGestureStart) {
  47141. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47142. }
  47143. if (this._onGesture) {
  47144. element.removeEventListener("MSGestureChange", this._onGesture);
  47145. }
  47146. this._isPanClick = false;
  47147. this.pinchInwards = true;
  47148. this._onMouseMove = null;
  47149. this._onGestureStart = null;
  47150. this._onGesture = null;
  47151. this._MSGestureHandler = null;
  47152. this._onLostFocus = null;
  47153. this._onContextMenu = null;
  47154. }
  47155. };
  47156. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47157. return "ArcRotateCameraPointersInput";
  47158. };
  47159. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47160. return "pointers";
  47161. };
  47162. __decorate([
  47163. BABYLON.serialize()
  47164. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47165. __decorate([
  47166. BABYLON.serialize()
  47167. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47168. __decorate([
  47169. BABYLON.serialize()
  47170. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47171. __decorate([
  47172. BABYLON.serialize()
  47173. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47174. __decorate([
  47175. BABYLON.serialize()
  47176. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47177. __decorate([
  47178. BABYLON.serialize()
  47179. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47180. __decorate([
  47181. BABYLON.serialize()
  47182. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47183. __decorate([
  47184. BABYLON.serialize()
  47185. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47186. return ArcRotateCameraPointersInput;
  47187. }());
  47188. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47189. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47190. })(BABYLON || (BABYLON = {}));
  47191. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47192. var BABYLON;
  47193. (function (BABYLON) {
  47194. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47195. __extends(ArcRotateCameraInputsManager, _super);
  47196. function ArcRotateCameraInputsManager(camera) {
  47197. return _super.call(this, camera) || this;
  47198. }
  47199. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47200. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47201. return this;
  47202. };
  47203. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47204. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47205. return this;
  47206. };
  47207. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47208. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47209. return this;
  47210. };
  47211. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47212. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47213. return this;
  47214. };
  47215. return ArcRotateCameraInputsManager;
  47216. }(BABYLON.CameraInputsManager));
  47217. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47218. })(BABYLON || (BABYLON = {}));
  47219. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47220. var BABYLON;
  47221. (function (BABYLON) {
  47222. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47223. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47224. });
  47225. var ArcRotateCamera = /** @class */ (function (_super) {
  47226. __extends(ArcRotateCamera, _super);
  47227. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47228. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47229. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47230. _this.inertialAlphaOffset = 0;
  47231. _this.inertialBetaOffset = 0;
  47232. _this.inertialRadiusOffset = 0;
  47233. _this.lowerAlphaLimit = null;
  47234. _this.upperAlphaLimit = null;
  47235. _this.lowerBetaLimit = 0.01;
  47236. _this.upperBetaLimit = Math.PI;
  47237. _this.lowerRadiusLimit = null;
  47238. _this.upperRadiusLimit = null;
  47239. _this.inertialPanningX = 0;
  47240. _this.inertialPanningY = 0;
  47241. _this.pinchToPanMaxDistance = 20;
  47242. _this.panningDistanceLimit = null;
  47243. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47244. _this.panningInertia = 0.9;
  47245. //-- end properties for backward compatibility for inputs
  47246. _this.zoomOnFactor = 1;
  47247. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47248. _this.allowUpsideDown = true;
  47249. _this._viewMatrix = new BABYLON.Matrix();
  47250. // Panning
  47251. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47252. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47253. _this.checkCollisions = false;
  47254. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47255. _this._previousPosition = BABYLON.Vector3.Zero();
  47256. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47257. _this._newPosition = BABYLON.Vector3.Zero();
  47258. _this._computationVector = BABYLON.Vector3.Zero();
  47259. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47260. if (collidedMesh === void 0) { collidedMesh = null; }
  47261. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47262. newPosition.multiplyInPlace(_this._collider._radius);
  47263. }
  47264. if (!collidedMesh) {
  47265. _this._previousPosition.copyFrom(_this.position);
  47266. }
  47267. else {
  47268. _this.setPosition(newPosition);
  47269. if (_this.onCollide) {
  47270. _this.onCollide(collidedMesh);
  47271. }
  47272. }
  47273. // Recompute because of constraints
  47274. var cosa = Math.cos(_this.alpha);
  47275. var sina = Math.sin(_this.alpha);
  47276. var cosb = Math.cos(_this.beta);
  47277. var sinb = Math.sin(_this.beta);
  47278. if (sinb === 0) {
  47279. sinb = 0.0001;
  47280. }
  47281. var target = _this._getTargetPosition();
  47282. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47283. target.addToRef(_this._computationVector, _this._newPosition);
  47284. _this.position.copyFrom(_this._newPosition);
  47285. var up = _this.upVector;
  47286. if (_this.allowUpsideDown && _this.beta < 0) {
  47287. up = up.clone();
  47288. up = up.negate();
  47289. }
  47290. _this._computeViewMatrix(_this.position, target, up);
  47291. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47292. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47293. _this._collisionTriggered = false;
  47294. };
  47295. _this._target = BABYLON.Vector3.Zero();
  47296. if (target) {
  47297. _this.setTarget(target);
  47298. }
  47299. _this.alpha = alpha;
  47300. _this.beta = beta;
  47301. _this.radius = radius;
  47302. _this.getViewMatrix();
  47303. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47304. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47305. return _this;
  47306. }
  47307. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47308. get: function () {
  47309. return this._target;
  47310. },
  47311. set: function (value) {
  47312. this.setTarget(value);
  47313. },
  47314. enumerable: true,
  47315. configurable: true
  47316. });
  47317. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47318. //-- begin properties for backward compatibility for inputs
  47319. get: function () {
  47320. var pointers = this.inputs.attached["pointers"];
  47321. if (pointers)
  47322. return pointers.angularSensibilityX;
  47323. return 0;
  47324. },
  47325. set: function (value) {
  47326. var pointers = this.inputs.attached["pointers"];
  47327. if (pointers) {
  47328. pointers.angularSensibilityX = value;
  47329. }
  47330. },
  47331. enumerable: true,
  47332. configurable: true
  47333. });
  47334. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47335. get: function () {
  47336. var pointers = this.inputs.attached["pointers"];
  47337. if (pointers)
  47338. return pointers.angularSensibilityY;
  47339. return 0;
  47340. },
  47341. set: function (value) {
  47342. var pointers = this.inputs.attached["pointers"];
  47343. if (pointers) {
  47344. pointers.angularSensibilityY = value;
  47345. }
  47346. },
  47347. enumerable: true,
  47348. configurable: true
  47349. });
  47350. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47351. get: function () {
  47352. var pointers = this.inputs.attached["pointers"];
  47353. if (pointers)
  47354. return pointers.pinchPrecision;
  47355. return 0;
  47356. },
  47357. set: function (value) {
  47358. var pointers = this.inputs.attached["pointers"];
  47359. if (pointers) {
  47360. pointers.pinchPrecision = value;
  47361. }
  47362. },
  47363. enumerable: true,
  47364. configurable: true
  47365. });
  47366. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47367. get: function () {
  47368. var pointers = this.inputs.attached["pointers"];
  47369. if (pointers)
  47370. return pointers.pinchDeltaPercentage;
  47371. return 0;
  47372. },
  47373. set: function (value) {
  47374. var pointers = this.inputs.attached["pointers"];
  47375. if (pointers) {
  47376. pointers.pinchDeltaPercentage = value;
  47377. }
  47378. },
  47379. enumerable: true,
  47380. configurable: true
  47381. });
  47382. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47383. get: function () {
  47384. var pointers = this.inputs.attached["pointers"];
  47385. if (pointers)
  47386. return pointers.panningSensibility;
  47387. return 0;
  47388. },
  47389. set: function (value) {
  47390. var pointers = this.inputs.attached["pointers"];
  47391. if (pointers) {
  47392. pointers.panningSensibility = value;
  47393. }
  47394. },
  47395. enumerable: true,
  47396. configurable: true
  47397. });
  47398. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47399. get: function () {
  47400. var keyboard = this.inputs.attached["keyboard"];
  47401. if (keyboard)
  47402. return keyboard.keysUp;
  47403. return [];
  47404. },
  47405. set: function (value) {
  47406. var keyboard = this.inputs.attached["keyboard"];
  47407. if (keyboard)
  47408. keyboard.keysUp = value;
  47409. },
  47410. enumerable: true,
  47411. configurable: true
  47412. });
  47413. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47414. get: function () {
  47415. var keyboard = this.inputs.attached["keyboard"];
  47416. if (keyboard)
  47417. return keyboard.keysDown;
  47418. return [];
  47419. },
  47420. set: function (value) {
  47421. var keyboard = this.inputs.attached["keyboard"];
  47422. if (keyboard)
  47423. keyboard.keysDown = value;
  47424. },
  47425. enumerable: true,
  47426. configurable: true
  47427. });
  47428. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47429. get: function () {
  47430. var keyboard = this.inputs.attached["keyboard"];
  47431. if (keyboard)
  47432. return keyboard.keysLeft;
  47433. return [];
  47434. },
  47435. set: function (value) {
  47436. var keyboard = this.inputs.attached["keyboard"];
  47437. if (keyboard)
  47438. keyboard.keysLeft = value;
  47439. },
  47440. enumerable: true,
  47441. configurable: true
  47442. });
  47443. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47444. get: function () {
  47445. var keyboard = this.inputs.attached["keyboard"];
  47446. if (keyboard)
  47447. return keyboard.keysRight;
  47448. return [];
  47449. },
  47450. set: function (value) {
  47451. var keyboard = this.inputs.attached["keyboard"];
  47452. if (keyboard)
  47453. keyboard.keysRight = value;
  47454. },
  47455. enumerable: true,
  47456. configurable: true
  47457. });
  47458. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47459. get: function () {
  47460. var mousewheel = this.inputs.attached["mousewheel"];
  47461. if (mousewheel)
  47462. return mousewheel.wheelPrecision;
  47463. return 0;
  47464. },
  47465. set: function (value) {
  47466. var mousewheel = this.inputs.attached["mousewheel"];
  47467. if (mousewheel)
  47468. mousewheel.wheelPrecision = value;
  47469. },
  47470. enumerable: true,
  47471. configurable: true
  47472. });
  47473. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47474. get: function () {
  47475. var mousewheel = this.inputs.attached["mousewheel"];
  47476. if (mousewheel)
  47477. return mousewheel.wheelDeltaPercentage;
  47478. return 0;
  47479. },
  47480. set: function (value) {
  47481. var mousewheel = this.inputs.attached["mousewheel"];
  47482. if (mousewheel)
  47483. mousewheel.wheelDeltaPercentage = value;
  47484. },
  47485. enumerable: true,
  47486. configurable: true
  47487. });
  47488. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47489. get: function () {
  47490. return this._bouncingBehavior;
  47491. },
  47492. enumerable: true,
  47493. configurable: true
  47494. });
  47495. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47496. get: function () {
  47497. return this._bouncingBehavior != null;
  47498. },
  47499. set: function (value) {
  47500. if (value === this.useBouncingBehavior) {
  47501. return;
  47502. }
  47503. if (value) {
  47504. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47505. this.addBehavior(this._bouncingBehavior);
  47506. }
  47507. else if (this._bouncingBehavior) {
  47508. this.removeBehavior(this._bouncingBehavior);
  47509. this._bouncingBehavior = null;
  47510. }
  47511. },
  47512. enumerable: true,
  47513. configurable: true
  47514. });
  47515. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47516. get: function () {
  47517. return this._framingBehavior;
  47518. },
  47519. enumerable: true,
  47520. configurable: true
  47521. });
  47522. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47523. get: function () {
  47524. return this._framingBehavior != null;
  47525. },
  47526. set: function (value) {
  47527. if (value === this.useFramingBehavior) {
  47528. return;
  47529. }
  47530. if (value) {
  47531. this._framingBehavior = new BABYLON.FramingBehavior();
  47532. this.addBehavior(this._framingBehavior);
  47533. }
  47534. else if (this._framingBehavior) {
  47535. this.removeBehavior(this._framingBehavior);
  47536. this._framingBehavior = null;
  47537. }
  47538. },
  47539. enumerable: true,
  47540. configurable: true
  47541. });
  47542. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47543. get: function () {
  47544. return this._autoRotationBehavior;
  47545. },
  47546. enumerable: true,
  47547. configurable: true
  47548. });
  47549. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47550. get: function () {
  47551. return this._autoRotationBehavior != null;
  47552. },
  47553. set: function (value) {
  47554. if (value === this.useAutoRotationBehavior) {
  47555. return;
  47556. }
  47557. if (value) {
  47558. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47559. this.addBehavior(this._autoRotationBehavior);
  47560. }
  47561. else if (this._autoRotationBehavior) {
  47562. this.removeBehavior(this._autoRotationBehavior);
  47563. this._autoRotationBehavior = null;
  47564. }
  47565. },
  47566. enumerable: true,
  47567. configurable: true
  47568. });
  47569. // Cache
  47570. ArcRotateCamera.prototype._initCache = function () {
  47571. _super.prototype._initCache.call(this);
  47572. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47573. this._cache.alpha = undefined;
  47574. this._cache.beta = undefined;
  47575. this._cache.radius = undefined;
  47576. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47577. };
  47578. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47579. if (!ignoreParentClass) {
  47580. _super.prototype._updateCache.call(this);
  47581. }
  47582. this._cache._target.copyFrom(this._getTargetPosition());
  47583. this._cache.alpha = this.alpha;
  47584. this._cache.beta = this.beta;
  47585. this._cache.radius = this.radius;
  47586. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47587. };
  47588. ArcRotateCamera.prototype._getTargetPosition = function () {
  47589. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47590. var pos = this._targetHost.getAbsolutePosition();
  47591. if (this._targetBoundingCenter) {
  47592. pos.addToRef(this._targetBoundingCenter, this._target);
  47593. }
  47594. else {
  47595. this._target.copyFrom(pos);
  47596. }
  47597. }
  47598. var lockedTargetPosition = this._getLockedTargetPosition();
  47599. if (lockedTargetPosition) {
  47600. return lockedTargetPosition;
  47601. }
  47602. return this._target;
  47603. };
  47604. ArcRotateCamera.prototype.storeState = function () {
  47605. this._storedAlpha = this.alpha;
  47606. this._storedBeta = this.beta;
  47607. this._storedRadius = this.radius;
  47608. this._storedTarget = this._getTargetPosition().clone();
  47609. return _super.prototype.storeState.call(this);
  47610. };
  47611. /**
  47612. * Restored camera state. You must call storeState() first
  47613. */
  47614. ArcRotateCamera.prototype._restoreStateValues = function () {
  47615. if (!_super.prototype._restoreStateValues.call(this)) {
  47616. return false;
  47617. }
  47618. this.alpha = this._storedAlpha;
  47619. this.beta = this._storedBeta;
  47620. this.radius = this._storedRadius;
  47621. this.setTarget(this._storedTarget.clone());
  47622. this.inertialAlphaOffset = 0;
  47623. this.inertialBetaOffset = 0;
  47624. this.inertialRadiusOffset = 0;
  47625. this.inertialPanningX = 0;
  47626. this.inertialPanningY = 0;
  47627. return true;
  47628. };
  47629. // Synchronized
  47630. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47631. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47632. return false;
  47633. return this._cache._target.equals(this._getTargetPosition())
  47634. && this._cache.alpha === this.alpha
  47635. && this._cache.beta === this.beta
  47636. && this._cache.radius === this.radius
  47637. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47638. };
  47639. // Methods
  47640. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47641. var _this = this;
  47642. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47643. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47644. this._useCtrlForPanning = useCtrlForPanning;
  47645. this._panningMouseButton = panningMouseButton;
  47646. this.inputs.attachElement(element, noPreventDefault);
  47647. this._reset = function () {
  47648. _this.inertialAlphaOffset = 0;
  47649. _this.inertialBetaOffset = 0;
  47650. _this.inertialRadiusOffset = 0;
  47651. _this.inertialPanningX = 0;
  47652. _this.inertialPanningY = 0;
  47653. };
  47654. };
  47655. ArcRotateCamera.prototype.detachControl = function (element) {
  47656. this.inputs.detachElement(element);
  47657. if (this._reset) {
  47658. this._reset();
  47659. }
  47660. };
  47661. ArcRotateCamera.prototype._checkInputs = function () {
  47662. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47663. if (this._collisionTriggered) {
  47664. return;
  47665. }
  47666. this.inputs.checkInputs();
  47667. // Inertia
  47668. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47669. var inertialAlphaOffset = this.inertialAlphaOffset;
  47670. if (this.beta <= 0)
  47671. inertialAlphaOffset *= -1;
  47672. if (this.getScene().useRightHandedSystem)
  47673. inertialAlphaOffset *= -1;
  47674. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47675. inertialAlphaOffset *= -1;
  47676. this.alpha += inertialAlphaOffset;
  47677. this.beta += this.inertialBetaOffset;
  47678. this.radius -= this.inertialRadiusOffset;
  47679. this.inertialAlphaOffset *= this.inertia;
  47680. this.inertialBetaOffset *= this.inertia;
  47681. this.inertialRadiusOffset *= this.inertia;
  47682. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47683. this.inertialAlphaOffset = 0;
  47684. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47685. this.inertialBetaOffset = 0;
  47686. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47687. this.inertialRadiusOffset = 0;
  47688. }
  47689. // Panning inertia
  47690. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47691. if (!this._localDirection) {
  47692. this._localDirection = BABYLON.Vector3.Zero();
  47693. this._transformedDirection = BABYLON.Vector3.Zero();
  47694. }
  47695. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47696. this._localDirection.multiplyInPlace(this.panningAxis);
  47697. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47698. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47699. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47700. if (!this.panningAxis.y) {
  47701. this._transformedDirection.y = 0;
  47702. }
  47703. if (!this._targetHost) {
  47704. if (this.panningDistanceLimit) {
  47705. this._transformedDirection.addInPlace(this._target);
  47706. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47707. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47708. this._target.copyFrom(this._transformedDirection);
  47709. }
  47710. }
  47711. else {
  47712. this._target.addInPlace(this._transformedDirection);
  47713. }
  47714. }
  47715. this.inertialPanningX *= this.panningInertia;
  47716. this.inertialPanningY *= this.panningInertia;
  47717. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47718. this.inertialPanningX = 0;
  47719. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47720. this.inertialPanningY = 0;
  47721. }
  47722. // Limits
  47723. this._checkLimits();
  47724. _super.prototype._checkInputs.call(this);
  47725. };
  47726. ArcRotateCamera.prototype._checkLimits = function () {
  47727. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47728. if (this.allowUpsideDown && this.beta > Math.PI) {
  47729. this.beta = this.beta - (2 * Math.PI);
  47730. }
  47731. }
  47732. else {
  47733. if (this.beta < this.lowerBetaLimit) {
  47734. this.beta = this.lowerBetaLimit;
  47735. }
  47736. }
  47737. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47738. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47739. this.beta = this.beta + (2 * Math.PI);
  47740. }
  47741. }
  47742. else {
  47743. if (this.beta > this.upperBetaLimit) {
  47744. this.beta = this.upperBetaLimit;
  47745. }
  47746. }
  47747. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  47748. this.alpha = this.lowerAlphaLimit;
  47749. }
  47750. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  47751. this.alpha = this.upperAlphaLimit;
  47752. }
  47753. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  47754. this.radius = this.lowerRadiusLimit;
  47755. }
  47756. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  47757. this.radius = this.upperRadiusLimit;
  47758. }
  47759. };
  47760. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47761. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47762. this.radius = this._computationVector.length();
  47763. if (this.radius === 0) {
  47764. this.radius = 0.0001; // Just to avoid division by zero
  47765. }
  47766. // Alpha
  47767. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47768. if (this._computationVector.z < 0) {
  47769. this.alpha = 2 * Math.PI - this.alpha;
  47770. }
  47771. // Beta
  47772. this.beta = Math.acos(this._computationVector.y / this.radius);
  47773. this._checkLimits();
  47774. };
  47775. ArcRotateCamera.prototype.setPosition = function (position) {
  47776. if (this.position.equals(position)) {
  47777. return;
  47778. }
  47779. this.position.copyFrom(position);
  47780. this.rebuildAnglesAndRadius();
  47781. };
  47782. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47783. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47784. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47785. if (target.getBoundingInfo) {
  47786. if (toBoundingCenter) {
  47787. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47788. }
  47789. else {
  47790. this._targetBoundingCenter = null;
  47791. }
  47792. this._targetHost = target;
  47793. this._target = this._getTargetPosition();
  47794. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47795. }
  47796. else {
  47797. var newTarget = target;
  47798. var currentTarget = this._getTargetPosition();
  47799. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47800. return;
  47801. }
  47802. this._targetHost = null;
  47803. this._target = newTarget;
  47804. this._targetBoundingCenter = null;
  47805. this.onMeshTargetChangedObservable.notifyObservers(null);
  47806. }
  47807. this.rebuildAnglesAndRadius();
  47808. };
  47809. ArcRotateCamera.prototype._getViewMatrix = function () {
  47810. // Compute
  47811. var cosa = Math.cos(this.alpha);
  47812. var sina = Math.sin(this.alpha);
  47813. var cosb = Math.cos(this.beta);
  47814. var sinb = Math.sin(this.beta);
  47815. if (sinb === 0) {
  47816. sinb = 0.0001;
  47817. }
  47818. var target = this._getTargetPosition();
  47819. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  47820. target.addToRef(this._computationVector, this._newPosition);
  47821. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  47822. if (!this._collider) {
  47823. this._collider = new BABYLON.Collider();
  47824. }
  47825. this._collider._radius = this.collisionRadius;
  47826. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  47827. this._collisionTriggered = true;
  47828. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47829. }
  47830. else {
  47831. this.position.copyFrom(this._newPosition);
  47832. var up = this.upVector;
  47833. if (this.allowUpsideDown && sinb < 0) {
  47834. up = up.clone();
  47835. up = up.negate();
  47836. }
  47837. this._computeViewMatrix(this.position, target, up);
  47838. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  47839. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  47840. }
  47841. this._currentTarget = target;
  47842. return this._viewMatrix;
  47843. };
  47844. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  47845. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47846. meshes = meshes || this.getScene().meshes;
  47847. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  47848. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  47849. this.radius = distance * this.zoomOnFactor;
  47850. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  47851. };
  47852. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  47853. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47854. var meshesOrMinMaxVector;
  47855. var distance;
  47856. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  47857. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  47858. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  47859. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  47860. }
  47861. else { //minMaxVector and distance
  47862. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  47863. meshesOrMinMaxVector = minMaxVectorAndDistance;
  47864. distance = minMaxVectorAndDistance.distance;
  47865. }
  47866. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  47867. if (!doNotUpdateMaxZ) {
  47868. this.maxZ = distance * 2;
  47869. }
  47870. };
  47871. /**
  47872. * @override
  47873. * Override Camera.createRigCamera
  47874. */
  47875. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47876. var alphaShift = 0;
  47877. switch (this.cameraRigMode) {
  47878. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47879. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47880. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47881. case BABYLON.Camera.RIG_MODE_VR:
  47882. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  47883. break;
  47884. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47885. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  47886. break;
  47887. }
  47888. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  47889. rigCam._cameraRigParams = {};
  47890. return rigCam;
  47891. };
  47892. /**
  47893. * @override
  47894. * Override Camera._updateRigCameras
  47895. */
  47896. ArcRotateCamera.prototype._updateRigCameras = function () {
  47897. var camLeft = this._rigCameras[0];
  47898. var camRight = this._rigCameras[1];
  47899. camLeft.beta = camRight.beta = this.beta;
  47900. camLeft.radius = camRight.radius = this.radius;
  47901. switch (this.cameraRigMode) {
  47902. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47903. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47904. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47905. case BABYLON.Camera.RIG_MODE_VR:
  47906. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47907. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47908. break;
  47909. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47910. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47911. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47912. break;
  47913. }
  47914. _super.prototype._updateRigCameras.call(this);
  47915. };
  47916. ArcRotateCamera.prototype.dispose = function () {
  47917. this.inputs.clear();
  47918. _super.prototype.dispose.call(this);
  47919. };
  47920. ArcRotateCamera.prototype.getClassName = function () {
  47921. return "ArcRotateCamera";
  47922. };
  47923. __decorate([
  47924. BABYLON.serialize()
  47925. ], ArcRotateCamera.prototype, "alpha", void 0);
  47926. __decorate([
  47927. BABYLON.serialize()
  47928. ], ArcRotateCamera.prototype, "beta", void 0);
  47929. __decorate([
  47930. BABYLON.serialize()
  47931. ], ArcRotateCamera.prototype, "radius", void 0);
  47932. __decorate([
  47933. BABYLON.serializeAsVector3("target")
  47934. ], ArcRotateCamera.prototype, "_target", void 0);
  47935. __decorate([
  47936. BABYLON.serialize()
  47937. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  47938. __decorate([
  47939. BABYLON.serialize()
  47940. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  47941. __decorate([
  47942. BABYLON.serialize()
  47943. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  47944. __decorate([
  47945. BABYLON.serialize()
  47946. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  47947. __decorate([
  47948. BABYLON.serialize()
  47949. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  47950. __decorate([
  47951. BABYLON.serialize()
  47952. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  47953. __decorate([
  47954. BABYLON.serialize()
  47955. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  47956. __decorate([
  47957. BABYLON.serialize()
  47958. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  47959. __decorate([
  47960. BABYLON.serialize()
  47961. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  47962. __decorate([
  47963. BABYLON.serialize()
  47964. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  47965. __decorate([
  47966. BABYLON.serialize()
  47967. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  47968. __decorate([
  47969. BABYLON.serialize()
  47970. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  47971. __decorate([
  47972. BABYLON.serialize()
  47973. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  47974. __decorate([
  47975. BABYLON.serializeAsVector3()
  47976. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  47977. __decorate([
  47978. BABYLON.serialize()
  47979. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  47980. __decorate([
  47981. BABYLON.serialize()
  47982. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  47983. __decorate([
  47984. BABYLON.serialize()
  47985. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  47986. return ArcRotateCamera;
  47987. }(BABYLON.TargetCamera));
  47988. BABYLON.ArcRotateCamera = ArcRotateCamera;
  47989. })(BABYLON || (BABYLON = {}));
  47990. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  47991. var BABYLON;
  47992. (function (BABYLON) {
  47993. /**
  47994. * The HemisphericLight simulates the ambient environment light,
  47995. * so the passed direction is the light reflection direction, not the incoming direction.
  47996. */
  47997. var HemisphericLight = /** @class */ (function (_super) {
  47998. __extends(HemisphericLight, _super);
  47999. /**
  48000. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48001. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48002. * The HemisphericLight can't cast shadows.
  48003. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48004. * @param name The friendly name of the light
  48005. * @param direction The direction of the light reflection
  48006. * @param scene The scene the light belongs to
  48007. */
  48008. function HemisphericLight(name, direction, scene) {
  48009. var _this = _super.call(this, name, scene) || this;
  48010. /**
  48011. * The groundColor is the light in the opposite direction to the one specified during creation.
  48012. * 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.
  48013. */
  48014. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48015. _this.direction = direction || BABYLON.Vector3.Up();
  48016. return _this;
  48017. }
  48018. HemisphericLight.prototype._buildUniformLayout = function () {
  48019. this._uniformBuffer.addUniform("vLightData", 4);
  48020. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48021. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48022. this._uniformBuffer.addUniform("vLightGround", 3);
  48023. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48024. this._uniformBuffer.addUniform("depthValues", 2);
  48025. this._uniformBuffer.create();
  48026. };
  48027. /**
  48028. * Returns the string "HemisphericLight".
  48029. * @return The class name
  48030. */
  48031. HemisphericLight.prototype.getClassName = function () {
  48032. return "HemisphericLight";
  48033. };
  48034. /**
  48035. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48036. * Returns the updated direction.
  48037. * @param target The target the direction should point to
  48038. * @return The computed direction
  48039. */
  48040. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48041. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48042. return this.direction;
  48043. };
  48044. /**
  48045. * Returns the shadow generator associated to the light.
  48046. * @returns Always null for hemispheric lights because it does not support shadows.
  48047. */
  48048. HemisphericLight.prototype.getShadowGenerator = function () {
  48049. return null;
  48050. };
  48051. /**
  48052. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48053. * @param effect The effect to update
  48054. * @param lightIndex The index of the light in the effect to update
  48055. * @returns The hemispheric light
  48056. */
  48057. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48058. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48059. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48060. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48061. return this;
  48062. };
  48063. /**
  48064. * @hidden internal use only.
  48065. */
  48066. HemisphericLight.prototype._getWorldMatrix = function () {
  48067. if (!this._worldMatrix) {
  48068. this._worldMatrix = BABYLON.Matrix.Identity();
  48069. }
  48070. return this._worldMatrix;
  48071. };
  48072. /**
  48073. * Returns the integer 3.
  48074. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48075. */
  48076. HemisphericLight.prototype.getTypeID = function () {
  48077. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48078. };
  48079. __decorate([
  48080. BABYLON.serializeAsColor3()
  48081. ], HemisphericLight.prototype, "groundColor", void 0);
  48082. __decorate([
  48083. BABYLON.serializeAsVector3()
  48084. ], HemisphericLight.prototype, "direction", void 0);
  48085. return HemisphericLight;
  48086. }(BABYLON.Light));
  48087. BABYLON.HemisphericLight = HemisphericLight;
  48088. })(BABYLON || (BABYLON = {}));
  48089. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48090. var BABYLON;
  48091. (function (BABYLON) {
  48092. /**
  48093. * Base implementation IShadowLight
  48094. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48095. */
  48096. var ShadowLight = /** @class */ (function (_super) {
  48097. __extends(ShadowLight, _super);
  48098. function ShadowLight() {
  48099. var _this = _super !== null && _super.apply(this, arguments) || this;
  48100. _this._needProjectionMatrixCompute = true;
  48101. return _this;
  48102. }
  48103. ShadowLight.prototype._setPosition = function (value) {
  48104. this._position = value;
  48105. };
  48106. Object.defineProperty(ShadowLight.prototype, "position", {
  48107. /**
  48108. * Sets the position the shadow will be casted from. Also use as the light position for both
  48109. * point and spot lights.
  48110. */
  48111. get: function () {
  48112. return this._position;
  48113. },
  48114. /**
  48115. * Sets the position the shadow will be casted from. Also use as the light position for both
  48116. * point and spot lights.
  48117. */
  48118. set: function (value) {
  48119. this._setPosition(value);
  48120. },
  48121. enumerable: true,
  48122. configurable: true
  48123. });
  48124. ShadowLight.prototype._setDirection = function (value) {
  48125. this._direction = value;
  48126. };
  48127. Object.defineProperty(ShadowLight.prototype, "direction", {
  48128. /**
  48129. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48130. * Also use as the light direction on spot and directional lights.
  48131. */
  48132. get: function () {
  48133. return this._direction;
  48134. },
  48135. /**
  48136. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48137. * Also use as the light direction on spot and directional lights.
  48138. */
  48139. set: function (value) {
  48140. this._setDirection(value);
  48141. },
  48142. enumerable: true,
  48143. configurable: true
  48144. });
  48145. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48146. /**
  48147. * Gets the shadow projection clipping minimum z value.
  48148. */
  48149. get: function () {
  48150. return this._shadowMinZ;
  48151. },
  48152. /**
  48153. * Sets the shadow projection clipping minimum z value.
  48154. */
  48155. set: function (value) {
  48156. this._shadowMinZ = value;
  48157. this.forceProjectionMatrixCompute();
  48158. },
  48159. enumerable: true,
  48160. configurable: true
  48161. });
  48162. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48163. /**
  48164. * Sets the shadow projection clipping maximum z value.
  48165. */
  48166. get: function () {
  48167. return this._shadowMaxZ;
  48168. },
  48169. /**
  48170. * Gets the shadow projection clipping maximum z value.
  48171. */
  48172. set: function (value) {
  48173. this._shadowMaxZ = value;
  48174. this.forceProjectionMatrixCompute();
  48175. },
  48176. enumerable: true,
  48177. configurable: true
  48178. });
  48179. /**
  48180. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48181. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48182. */
  48183. ShadowLight.prototype.computeTransformedInformation = function () {
  48184. if (this.parent && this.parent.getWorldMatrix) {
  48185. if (!this.transformedPosition) {
  48186. this.transformedPosition = BABYLON.Vector3.Zero();
  48187. }
  48188. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48189. // In case the direction is present.
  48190. if (this.direction) {
  48191. if (!this.transformedDirection) {
  48192. this.transformedDirection = BABYLON.Vector3.Zero();
  48193. }
  48194. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48195. }
  48196. return true;
  48197. }
  48198. return false;
  48199. };
  48200. /**
  48201. * Return the depth scale used for the shadow map.
  48202. * @returns the depth scale.
  48203. */
  48204. ShadowLight.prototype.getDepthScale = function () {
  48205. return 50.0;
  48206. };
  48207. /**
  48208. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48209. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48210. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48211. */
  48212. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48213. return this.transformedDirection ? this.transformedDirection : this.direction;
  48214. };
  48215. /**
  48216. * Returns the ShadowLight absolute position in the World.
  48217. * @returns the position vector in world space
  48218. */
  48219. ShadowLight.prototype.getAbsolutePosition = function () {
  48220. return this.transformedPosition ? this.transformedPosition : this.position;
  48221. };
  48222. /**
  48223. * Sets the ShadowLight direction toward the passed target.
  48224. * @param target The point tot target in local space
  48225. * @returns the updated ShadowLight direction
  48226. */
  48227. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48228. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48229. return this.direction;
  48230. };
  48231. /**
  48232. * Returns the light rotation in euler definition.
  48233. * @returns the x y z rotation in local space.
  48234. */
  48235. ShadowLight.prototype.getRotation = function () {
  48236. this.direction.normalize();
  48237. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48238. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48239. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48240. };
  48241. /**
  48242. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48243. * @returns true if a cube texture needs to be use
  48244. */
  48245. ShadowLight.prototype.needCube = function () {
  48246. return false;
  48247. };
  48248. /**
  48249. * Detects if the projection matrix requires to be recomputed this frame.
  48250. * @returns true if it requires to be recomputed otherwise, false.
  48251. */
  48252. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48253. return this._needProjectionMatrixCompute;
  48254. };
  48255. /**
  48256. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48257. */
  48258. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48259. this._needProjectionMatrixCompute = true;
  48260. };
  48261. /**
  48262. * Get the world matrix of the sahdow lights.
  48263. * @hidden Internal Use Only
  48264. */
  48265. ShadowLight.prototype._getWorldMatrix = function () {
  48266. if (!this._worldMatrix) {
  48267. this._worldMatrix = BABYLON.Matrix.Identity();
  48268. }
  48269. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48270. return this._worldMatrix;
  48271. };
  48272. /**
  48273. * Gets the minZ used for shadow according to both the scene and the light.
  48274. * @param activeCamera The camera we are returning the min for
  48275. * @returns the depth min z
  48276. */
  48277. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48278. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48279. };
  48280. /**
  48281. * Gets the maxZ used for shadow according to both the scene and the light.
  48282. * @param activeCamera The camera we are returning the max for
  48283. * @returns the depth max z
  48284. */
  48285. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48286. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48287. };
  48288. /**
  48289. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48290. * @param matrix The materix to updated with the projection information
  48291. * @param viewMatrix The transform matrix of the light
  48292. * @param renderList The list of mesh to render in the map
  48293. * @returns The current light
  48294. */
  48295. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48296. if (this.customProjectionMatrixBuilder) {
  48297. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48298. }
  48299. else {
  48300. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48301. }
  48302. return this;
  48303. };
  48304. __decorate([
  48305. BABYLON.serializeAsVector3()
  48306. ], ShadowLight.prototype, "position", null);
  48307. __decorate([
  48308. BABYLON.serializeAsVector3()
  48309. ], ShadowLight.prototype, "direction", null);
  48310. __decorate([
  48311. BABYLON.serialize()
  48312. ], ShadowLight.prototype, "shadowMinZ", null);
  48313. __decorate([
  48314. BABYLON.serialize()
  48315. ], ShadowLight.prototype, "shadowMaxZ", null);
  48316. return ShadowLight;
  48317. }(BABYLON.Light));
  48318. BABYLON.ShadowLight = ShadowLight;
  48319. })(BABYLON || (BABYLON = {}));
  48320. //# sourceMappingURL=babylon.shadowLight.js.map
  48321. var BABYLON;
  48322. (function (BABYLON) {
  48323. /**
  48324. * A point light is a light defined by an unique point in world space.
  48325. * The light is emitted in every direction from this point.
  48326. * A good example of a point light is a standard light bulb.
  48327. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48328. */
  48329. var PointLight = /** @class */ (function (_super) {
  48330. __extends(PointLight, _super);
  48331. /**
  48332. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48333. * A PointLight emits the light in every direction.
  48334. * It can cast shadows.
  48335. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48336. * ```javascript
  48337. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48338. * ```
  48339. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48340. * @param name The light friendly name
  48341. * @param position The position of the point light in the scene
  48342. * @param scene The scene the lights belongs to
  48343. */
  48344. function PointLight(name, position, scene) {
  48345. var _this = _super.call(this, name, scene) || this;
  48346. _this._shadowAngle = Math.PI / 2;
  48347. _this.position = position;
  48348. return _this;
  48349. }
  48350. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48351. /**
  48352. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48353. * This specifies what angle the shadow will use to be created.
  48354. *
  48355. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48356. */
  48357. get: function () {
  48358. return this._shadowAngle;
  48359. },
  48360. /**
  48361. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48362. * This specifies what angle the shadow will use to be created.
  48363. *
  48364. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48365. */
  48366. set: function (value) {
  48367. this._shadowAngle = value;
  48368. this.forceProjectionMatrixCompute();
  48369. },
  48370. enumerable: true,
  48371. configurable: true
  48372. });
  48373. Object.defineProperty(PointLight.prototype, "direction", {
  48374. /**
  48375. * Gets the direction if it has been set.
  48376. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48377. */
  48378. get: function () {
  48379. return this._direction;
  48380. },
  48381. /**
  48382. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48383. */
  48384. set: function (value) {
  48385. var previousNeedCube = this.needCube();
  48386. this._direction = value;
  48387. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48388. this._shadowGenerator.recreateShadowMap();
  48389. }
  48390. },
  48391. enumerable: true,
  48392. configurable: true
  48393. });
  48394. /**
  48395. * Returns the string "PointLight"
  48396. * @returns the class name
  48397. */
  48398. PointLight.prototype.getClassName = function () {
  48399. return "PointLight";
  48400. };
  48401. /**
  48402. * Returns the integer 0.
  48403. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48404. */
  48405. PointLight.prototype.getTypeID = function () {
  48406. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48407. };
  48408. /**
  48409. * Specifies wether or not the shadowmap should be a cube texture.
  48410. * @returns true if the shadowmap needs to be a cube texture.
  48411. */
  48412. PointLight.prototype.needCube = function () {
  48413. return !this.direction;
  48414. };
  48415. /**
  48416. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48417. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48418. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48419. */
  48420. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48421. if (this.direction) {
  48422. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48423. }
  48424. else {
  48425. switch (faceIndex) {
  48426. case 0:
  48427. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48428. case 1:
  48429. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48430. case 2:
  48431. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48432. case 3:
  48433. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48434. case 4:
  48435. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48436. case 5:
  48437. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48438. }
  48439. }
  48440. return BABYLON.Vector3.Zero();
  48441. };
  48442. /**
  48443. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48444. * - fov = PI / 2
  48445. * - aspect ratio : 1.0
  48446. * - z-near and far equal to the active camera minZ and maxZ.
  48447. * Returns the PointLight.
  48448. */
  48449. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48450. var activeCamera = this.getScene().activeCamera;
  48451. if (!activeCamera) {
  48452. return;
  48453. }
  48454. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48455. };
  48456. PointLight.prototype._buildUniformLayout = function () {
  48457. this._uniformBuffer.addUniform("vLightData", 4);
  48458. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48459. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48460. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48461. this._uniformBuffer.addUniform("depthValues", 2);
  48462. this._uniformBuffer.create();
  48463. };
  48464. /**
  48465. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48466. * @param effect The effect to update
  48467. * @param lightIndex The index of the light in the effect to update
  48468. * @returns The point light
  48469. */
  48470. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48471. if (this.computeTransformedInformation()) {
  48472. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48473. return this;
  48474. }
  48475. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48476. return this;
  48477. };
  48478. __decorate([
  48479. BABYLON.serialize()
  48480. ], PointLight.prototype, "shadowAngle", null);
  48481. return PointLight;
  48482. }(BABYLON.ShadowLight));
  48483. BABYLON.PointLight = PointLight;
  48484. })(BABYLON || (BABYLON = {}));
  48485. //# sourceMappingURL=babylon.pointLight.js.map
  48486. var BABYLON;
  48487. (function (BABYLON) {
  48488. /**
  48489. * A directional light is defined by a direction (what a surprise!).
  48490. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48491. * 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.
  48492. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48493. */
  48494. var DirectionalLight = /** @class */ (function (_super) {
  48495. __extends(DirectionalLight, _super);
  48496. /**
  48497. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48498. * The directional light is emitted from everywhere in the given direction.
  48499. * It can cast shawdows.
  48500. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48501. * @param name The friendly name of the light
  48502. * @param direction The direction of the light
  48503. * @param scene The scene the light belongs to
  48504. */
  48505. function DirectionalLight(name, direction, scene) {
  48506. var _this = _super.call(this, name, scene) || this;
  48507. _this._shadowFrustumSize = 0;
  48508. _this._shadowOrthoScale = 0.1;
  48509. /**
  48510. * Automatically compute the projection matrix to best fit (including all the casters)
  48511. * on each frame.
  48512. */
  48513. _this.autoUpdateExtends = true;
  48514. // Cache
  48515. _this._orthoLeft = Number.MAX_VALUE;
  48516. _this._orthoRight = Number.MIN_VALUE;
  48517. _this._orthoTop = Number.MIN_VALUE;
  48518. _this._orthoBottom = Number.MAX_VALUE;
  48519. _this.position = direction.scale(-1.0);
  48520. _this.direction = direction;
  48521. return _this;
  48522. }
  48523. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48524. /**
  48525. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48526. */
  48527. get: function () {
  48528. return this._shadowFrustumSize;
  48529. },
  48530. /**
  48531. * Specifies a fix frustum size for the shadow generation.
  48532. */
  48533. set: function (value) {
  48534. this._shadowFrustumSize = value;
  48535. this.forceProjectionMatrixCompute();
  48536. },
  48537. enumerable: true,
  48538. configurable: true
  48539. });
  48540. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48541. /**
  48542. * Gets the shadow projection scale against the optimal computed one.
  48543. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48544. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48545. */
  48546. get: function () {
  48547. return this._shadowOrthoScale;
  48548. },
  48549. /**
  48550. * Sets the shadow projection scale against the optimal computed one.
  48551. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48552. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48553. */
  48554. set: function (value) {
  48555. this._shadowOrthoScale = value;
  48556. this.forceProjectionMatrixCompute();
  48557. },
  48558. enumerable: true,
  48559. configurable: true
  48560. });
  48561. /**
  48562. * Returns the string "DirectionalLight".
  48563. * @return The class name
  48564. */
  48565. DirectionalLight.prototype.getClassName = function () {
  48566. return "DirectionalLight";
  48567. };
  48568. /**
  48569. * Returns the integer 1.
  48570. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48571. */
  48572. DirectionalLight.prototype.getTypeID = function () {
  48573. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48574. };
  48575. /**
  48576. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48577. * Returns the DirectionalLight Shadow projection matrix.
  48578. */
  48579. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48580. if (this.shadowFrustumSize > 0) {
  48581. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48582. }
  48583. else {
  48584. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48585. }
  48586. };
  48587. /**
  48588. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48589. * Returns the DirectionalLight Shadow projection matrix.
  48590. */
  48591. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48592. var activeCamera = this.getScene().activeCamera;
  48593. if (!activeCamera) {
  48594. return;
  48595. }
  48596. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48597. };
  48598. /**
  48599. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48600. * Returns the DirectionalLight Shadow projection matrix.
  48601. */
  48602. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48603. var activeCamera = this.getScene().activeCamera;
  48604. if (!activeCamera) {
  48605. return;
  48606. }
  48607. // Check extends
  48608. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48609. var tempVector3 = BABYLON.Vector3.Zero();
  48610. this._orthoLeft = Number.MAX_VALUE;
  48611. this._orthoRight = Number.MIN_VALUE;
  48612. this._orthoTop = Number.MIN_VALUE;
  48613. this._orthoBottom = Number.MAX_VALUE;
  48614. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48615. var mesh = renderList[meshIndex];
  48616. if (!mesh) {
  48617. continue;
  48618. }
  48619. var boundingInfo = mesh.getBoundingInfo();
  48620. var boundingBox = boundingInfo.boundingBox;
  48621. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48622. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48623. if (tempVector3.x < this._orthoLeft)
  48624. this._orthoLeft = tempVector3.x;
  48625. if (tempVector3.y < this._orthoBottom)
  48626. this._orthoBottom = tempVector3.y;
  48627. if (tempVector3.x > this._orthoRight)
  48628. this._orthoRight = tempVector3.x;
  48629. if (tempVector3.y > this._orthoTop)
  48630. this._orthoTop = tempVector3.y;
  48631. }
  48632. }
  48633. }
  48634. var xOffset = this._orthoRight - this._orthoLeft;
  48635. var yOffset = this._orthoTop - this._orthoBottom;
  48636. 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);
  48637. };
  48638. DirectionalLight.prototype._buildUniformLayout = function () {
  48639. this._uniformBuffer.addUniform("vLightData", 4);
  48640. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48641. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48642. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48643. this._uniformBuffer.addUniform("depthValues", 2);
  48644. this._uniformBuffer.create();
  48645. };
  48646. /**
  48647. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48648. * @param effect The effect to update
  48649. * @param lightIndex The index of the light in the effect to update
  48650. * @returns The directional light
  48651. */
  48652. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48653. if (this.computeTransformedInformation()) {
  48654. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48655. return this;
  48656. }
  48657. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48658. return this;
  48659. };
  48660. /**
  48661. * Gets the minZ used for shadow according to both the scene and the light.
  48662. *
  48663. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48664. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48665. * @param activeCamera The camera we are returning the min for
  48666. * @returns the depth min z
  48667. */
  48668. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48669. return 1;
  48670. };
  48671. /**
  48672. * Gets the maxZ used for shadow according to both the scene and the light.
  48673. *
  48674. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48675. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48676. * @param activeCamera The camera we are returning the max for
  48677. * @returns the depth max z
  48678. */
  48679. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48680. return 1;
  48681. };
  48682. __decorate([
  48683. BABYLON.serialize()
  48684. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48685. __decorate([
  48686. BABYLON.serialize()
  48687. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48688. __decorate([
  48689. BABYLON.serialize()
  48690. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48691. return DirectionalLight;
  48692. }(BABYLON.ShadowLight));
  48693. BABYLON.DirectionalLight = DirectionalLight;
  48694. })(BABYLON || (BABYLON = {}));
  48695. //# sourceMappingURL=babylon.directionalLight.js.map
  48696. var BABYLON;
  48697. (function (BABYLON) {
  48698. /**
  48699. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48700. * These values define a cone of light starting from the position, emitting toward the direction.
  48701. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48702. * and the exponent defines the speed of the decay of the light with distance (reach).
  48703. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48704. */
  48705. var SpotLight = /** @class */ (function (_super) {
  48706. __extends(SpotLight, _super);
  48707. /**
  48708. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48709. * It can cast shadows.
  48710. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48711. * @param name The light friendly name
  48712. * @param position The position of the spot light in the scene
  48713. * @param direction The direction of the light in the scene
  48714. * @param angle The cone angle of the light in Radians
  48715. * @param exponent The light decay speed with the distance from the emission spot
  48716. * @param scene The scene the lights belongs to
  48717. */
  48718. function SpotLight(name, position, direction, angle, exponent, scene) {
  48719. var _this = _super.call(this, name, scene) || this;
  48720. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48721. _this._projectionTextureLightNear = 1e-6;
  48722. _this._projectionTextureLightFar = 1000.0;
  48723. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48724. _this._projectionTextureViewLightDirty = true;
  48725. _this._projectionTextureProjectionLightDirty = true;
  48726. _this._projectionTextureDirty = true;
  48727. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48728. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48729. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48730. _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);
  48731. _this.position = position;
  48732. _this.direction = direction;
  48733. _this.angle = angle;
  48734. _this.exponent = exponent;
  48735. return _this;
  48736. }
  48737. Object.defineProperty(SpotLight.prototype, "angle", {
  48738. /**
  48739. * Gets the cone angle of the spot light in Radians.
  48740. */
  48741. get: function () {
  48742. return this._angle;
  48743. },
  48744. /**
  48745. * Sets the cone angle of the spot light in Radians.
  48746. */
  48747. set: function (value) {
  48748. this._angle = value;
  48749. this._projectionTextureProjectionLightDirty = true;
  48750. this.forceProjectionMatrixCompute();
  48751. },
  48752. enumerable: true,
  48753. configurable: true
  48754. });
  48755. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48756. /**
  48757. * Allows scaling the angle of the light for shadow generation only.
  48758. */
  48759. get: function () {
  48760. return this._shadowAngleScale;
  48761. },
  48762. /**
  48763. * Allows scaling the angle of the light for shadow generation only.
  48764. */
  48765. set: function (value) {
  48766. this._shadowAngleScale = value;
  48767. this.forceProjectionMatrixCompute();
  48768. },
  48769. enumerable: true,
  48770. configurable: true
  48771. });
  48772. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48773. /**
  48774. * Allows reading the projecton texture
  48775. */
  48776. get: function () {
  48777. return this._projectionTextureMatrix;
  48778. },
  48779. enumerable: true,
  48780. configurable: true
  48781. });
  48782. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48783. /**
  48784. * Gets the near clip of the Spotlight for texture projection.
  48785. */
  48786. get: function () {
  48787. return this._projectionTextureLightNear;
  48788. },
  48789. /**
  48790. * Sets the near clip of the Spotlight for texture projection.
  48791. */
  48792. set: function (value) {
  48793. this._projectionTextureLightNear = value;
  48794. this._projectionTextureProjectionLightDirty = true;
  48795. },
  48796. enumerable: true,
  48797. configurable: true
  48798. });
  48799. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48800. /**
  48801. * Gets the far clip of the Spotlight for texture projection.
  48802. */
  48803. get: function () {
  48804. return this._projectionTextureLightFar;
  48805. },
  48806. /**
  48807. * Sets the far clip of the Spotlight for texture projection.
  48808. */
  48809. set: function (value) {
  48810. this._projectionTextureLightFar = value;
  48811. this._projectionTextureProjectionLightDirty = true;
  48812. },
  48813. enumerable: true,
  48814. configurable: true
  48815. });
  48816. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  48817. /**
  48818. * Gets the Up vector of the Spotlight for texture projection.
  48819. */
  48820. get: function () {
  48821. return this._projectionTextureUpDirection;
  48822. },
  48823. /**
  48824. * Sets the Up vector of the Spotlight for texture projection.
  48825. */
  48826. set: function (value) {
  48827. this._projectionTextureUpDirection = value;
  48828. this._projectionTextureProjectionLightDirty = true;
  48829. },
  48830. enumerable: true,
  48831. configurable: true
  48832. });
  48833. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  48834. /**
  48835. * Gets the projection texture of the light.
  48836. */
  48837. get: function () {
  48838. return this._projectionTexture;
  48839. },
  48840. /**
  48841. * Sets the projection texture of the light.
  48842. */
  48843. set: function (value) {
  48844. this._projectionTexture = value;
  48845. this._projectionTextureDirty = true;
  48846. },
  48847. enumerable: true,
  48848. configurable: true
  48849. });
  48850. /**
  48851. * Returns the string "SpotLight".
  48852. * @returns the class name
  48853. */
  48854. SpotLight.prototype.getClassName = function () {
  48855. return "SpotLight";
  48856. };
  48857. /**
  48858. * Returns the integer 2.
  48859. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48860. */
  48861. SpotLight.prototype.getTypeID = function () {
  48862. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  48863. };
  48864. /**
  48865. * Overrides the direction setter to recompute the projection texture view light Matrix.
  48866. */
  48867. SpotLight.prototype._setDirection = function (value) {
  48868. _super.prototype._setDirection.call(this, value);
  48869. this._projectionTextureViewLightDirty = true;
  48870. };
  48871. /**
  48872. * Overrides the position setter to recompute the projection texture view light Matrix.
  48873. */
  48874. SpotLight.prototype._setPosition = function (value) {
  48875. _super.prototype._setPosition.call(this, value);
  48876. this._projectionTextureViewLightDirty = true;
  48877. };
  48878. /**
  48879. * 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.
  48880. * Returns the SpotLight.
  48881. */
  48882. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48883. var activeCamera = this.getScene().activeCamera;
  48884. if (!activeCamera) {
  48885. return;
  48886. }
  48887. this._shadowAngleScale = this._shadowAngleScale || 1;
  48888. var angle = this._shadowAngleScale * this._angle;
  48889. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48890. };
  48891. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  48892. this._projectionTextureViewLightDirty = false;
  48893. this._projectionTextureDirty = true;
  48894. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  48895. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  48896. };
  48897. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  48898. this._projectionTextureProjectionLightDirty = false;
  48899. this._projectionTextureDirty = true;
  48900. var light_far = this.projectionTextureLightFar;
  48901. var light_near = this.projectionTextureLightNear;
  48902. var P = light_far / (light_far - light_near);
  48903. var Q = -P * light_near;
  48904. var S = 1.0 / Math.tan(this._angle / 2.0);
  48905. var A = 1.0;
  48906. 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);
  48907. };
  48908. /**
  48909. * Main function for light texture projection matrix computing.
  48910. */
  48911. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  48912. this._projectionTextureDirty = false;
  48913. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  48914. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  48915. };
  48916. SpotLight.prototype._buildUniformLayout = function () {
  48917. this._uniformBuffer.addUniform("vLightData", 4);
  48918. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48919. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48920. this._uniformBuffer.addUniform("vLightDirection", 3);
  48921. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48922. this._uniformBuffer.addUniform("depthValues", 2);
  48923. this._uniformBuffer.create();
  48924. };
  48925. /**
  48926. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  48927. * @param effect The effect to update
  48928. * @param lightIndex The index of the light in the effect to update
  48929. * @returns The spot light
  48930. */
  48931. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  48932. var normalizeDirection;
  48933. if (this.computeTransformedInformation()) {
  48934. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  48935. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  48936. }
  48937. else {
  48938. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  48939. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48940. }
  48941. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  48942. if (this.projectionTexture && this.projectionTexture.isReady()) {
  48943. if (this._projectionTextureViewLightDirty) {
  48944. this._computeProjectionTextureViewLightMatrix();
  48945. }
  48946. if (this._projectionTextureProjectionLightDirty) {
  48947. this._computeProjectionTextureProjectionLightMatrix();
  48948. }
  48949. if (this._projectionTextureDirty) {
  48950. this._computeProjectionTextureMatrix();
  48951. }
  48952. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  48953. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  48954. }
  48955. return this;
  48956. };
  48957. /**
  48958. * Disposes the light and the associated resources.
  48959. */
  48960. SpotLight.prototype.dispose = function () {
  48961. _super.prototype.dispose.call(this);
  48962. if (this._projectionTexture) {
  48963. this._projectionTexture.dispose();
  48964. }
  48965. };
  48966. __decorate([
  48967. BABYLON.serialize()
  48968. ], SpotLight.prototype, "angle", null);
  48969. __decorate([
  48970. BABYLON.serialize()
  48971. ], SpotLight.prototype, "shadowAngleScale", null);
  48972. __decorate([
  48973. BABYLON.serialize()
  48974. ], SpotLight.prototype, "exponent", void 0);
  48975. __decorate([
  48976. BABYLON.serialize()
  48977. ], SpotLight.prototype, "projectionTextureLightNear", null);
  48978. __decorate([
  48979. BABYLON.serialize()
  48980. ], SpotLight.prototype, "projectionTextureLightFar", null);
  48981. __decorate([
  48982. BABYLON.serialize()
  48983. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  48984. __decorate([
  48985. BABYLON.serializeAsTexture("projectedLightTexture")
  48986. ], SpotLight.prototype, "_projectionTexture", void 0);
  48987. return SpotLight;
  48988. }(BABYLON.ShadowLight));
  48989. BABYLON.SpotLight = SpotLight;
  48990. })(BABYLON || (BABYLON = {}));
  48991. //# sourceMappingURL=babylon.spotLight.js.map
  48992. var BABYLON;
  48993. (function (BABYLON) {
  48994. /**
  48995. * Class used to override all child animations of a given target
  48996. */
  48997. var AnimationPropertiesOverride = /** @class */ (function () {
  48998. function AnimationPropertiesOverride() {
  48999. /**
  49000. * Gets or sets a value indicating if animation blending must be used
  49001. */
  49002. this.enableBlending = false;
  49003. /**
  49004. * Gets or sets the blending speed to use when enableBlending is true
  49005. */
  49006. this.blendingSpeed = 0.01;
  49007. /**
  49008. * Gets or sets the default loop mode to use
  49009. */
  49010. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49011. }
  49012. return AnimationPropertiesOverride;
  49013. }());
  49014. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49015. })(BABYLON || (BABYLON = {}));
  49016. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49017. var BABYLON;
  49018. (function (BABYLON) {
  49019. /**
  49020. * Represents the range of an animation
  49021. */
  49022. var AnimationRange = /** @class */ (function () {
  49023. /**
  49024. * Initializes the range of an animation
  49025. * @param name The name of the animation range
  49026. * @param from The starting frame of the animation
  49027. * @param to The ending frame of the animation
  49028. */
  49029. function AnimationRange(
  49030. /**The name of the animation range**/
  49031. name,
  49032. /**The starting frame of the animation */
  49033. from,
  49034. /**The ending frame of the animation*/
  49035. to) {
  49036. this.name = name;
  49037. this.from = from;
  49038. this.to = to;
  49039. }
  49040. /**
  49041. * Makes a copy of the animation range
  49042. * @returns A copy of the animation range
  49043. */
  49044. AnimationRange.prototype.clone = function () {
  49045. return new AnimationRange(this.name, this.from, this.to);
  49046. };
  49047. return AnimationRange;
  49048. }());
  49049. BABYLON.AnimationRange = AnimationRange;
  49050. /**
  49051. * Composed of a frame, and an action function
  49052. */
  49053. var AnimationEvent = /** @class */ (function () {
  49054. /**
  49055. * Initializes the animation event
  49056. * @param frame The frame for which the event is triggered
  49057. * @param action The event to perform when triggered
  49058. * @param onlyOnce Specifies if the event should be triggered only once
  49059. */
  49060. function AnimationEvent(
  49061. /** The frame for which the event is triggered **/
  49062. frame,
  49063. /** The event to perform when triggered **/
  49064. action,
  49065. /** Specifies if the event should be triggered only once**/
  49066. onlyOnce) {
  49067. this.frame = frame;
  49068. this.action = action;
  49069. this.onlyOnce = onlyOnce;
  49070. /**
  49071. * Specifies if the animation event is done
  49072. */
  49073. this.isDone = false;
  49074. }
  49075. /** @hidden */
  49076. AnimationEvent.prototype._clone = function () {
  49077. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49078. };
  49079. return AnimationEvent;
  49080. }());
  49081. BABYLON.AnimationEvent = AnimationEvent;
  49082. /**
  49083. * A cursor which tracks a point on a path
  49084. */
  49085. var PathCursor = /** @class */ (function () {
  49086. /**
  49087. * Initializes the path cursor
  49088. * @param path The path to track
  49089. */
  49090. function PathCursor(path) {
  49091. this.path = path;
  49092. /**
  49093. * Stores path cursor callbacks for when an onchange event is triggered
  49094. */
  49095. this._onchange = new Array();
  49096. /**
  49097. * The value of the path cursor
  49098. */
  49099. this.value = 0;
  49100. /**
  49101. * The animation array of the path cursor
  49102. */
  49103. this.animations = new Array();
  49104. }
  49105. /**
  49106. * Gets the cursor point on the path
  49107. * @returns A point on the path cursor at the cursor location
  49108. */
  49109. PathCursor.prototype.getPoint = function () {
  49110. var point = this.path.getPointAtLengthPosition(this.value);
  49111. return new BABYLON.Vector3(point.x, 0, point.y);
  49112. };
  49113. /**
  49114. * Moves the cursor ahead by the step amount
  49115. * @param step The amount to move the cursor forward
  49116. * @returns This path cursor
  49117. */
  49118. PathCursor.prototype.moveAhead = function (step) {
  49119. if (step === void 0) { step = 0.002; }
  49120. this.move(step);
  49121. return this;
  49122. };
  49123. /**
  49124. * Moves the cursor behind by the step amount
  49125. * @param step The amount to move the cursor back
  49126. * @returns This path cursor
  49127. */
  49128. PathCursor.prototype.moveBack = function (step) {
  49129. if (step === void 0) { step = 0.002; }
  49130. this.move(-step);
  49131. return this;
  49132. };
  49133. /**
  49134. * Moves the cursor by the step amount
  49135. * If the step amount is greater than one, an exception is thrown
  49136. * @param step The amount to move the cursor
  49137. * @returns This path cursor
  49138. */
  49139. PathCursor.prototype.move = function (step) {
  49140. if (Math.abs(step) > 1) {
  49141. throw "step size should be less than 1.";
  49142. }
  49143. this.value += step;
  49144. this.ensureLimits();
  49145. this.raiseOnChange();
  49146. return this;
  49147. };
  49148. /**
  49149. * Ensures that the value is limited between zero and one
  49150. * @returns This path cursor
  49151. */
  49152. PathCursor.prototype.ensureLimits = function () {
  49153. while (this.value > 1) {
  49154. this.value -= 1;
  49155. }
  49156. while (this.value < 0) {
  49157. this.value += 1;
  49158. }
  49159. return this;
  49160. };
  49161. /**
  49162. * Runs onchange callbacks on change (used by the animation engine)
  49163. * @returns This path cursor
  49164. */
  49165. PathCursor.prototype.raiseOnChange = function () {
  49166. var _this = this;
  49167. this._onchange.forEach(function (f) { return f(_this); });
  49168. return this;
  49169. };
  49170. /**
  49171. * Executes a function on change
  49172. * @param f A path cursor onchange callback
  49173. * @returns This path cursor
  49174. */
  49175. PathCursor.prototype.onchange = function (f) {
  49176. this._onchange.push(f);
  49177. return this;
  49178. };
  49179. return PathCursor;
  49180. }());
  49181. BABYLON.PathCursor = PathCursor;
  49182. /**
  49183. * Enum for the animation key frame interpolation type
  49184. */
  49185. var AnimationKeyInterpolation;
  49186. (function (AnimationKeyInterpolation) {
  49187. /**
  49188. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49189. */
  49190. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49191. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49192. /**
  49193. * Class used to store any kind of animation
  49194. */
  49195. var Animation = /** @class */ (function () {
  49196. /**
  49197. * Initializes the animation
  49198. * @param name Name of the animation
  49199. * @param targetProperty Property to animate
  49200. * @param framePerSecond The frames per second of the animation
  49201. * @param dataType The data type of the animation
  49202. * @param loopMode The loop mode of the animation
  49203. * @param enableBlendings Specifies if blending should be enabled
  49204. */
  49205. function Animation(
  49206. /**Name of the animation */
  49207. name,
  49208. /**Property to animate */
  49209. targetProperty,
  49210. /**The frames per second of the animation */
  49211. framePerSecond,
  49212. /**The data type of the animation */
  49213. dataType,
  49214. /**The loop mode of the animation */
  49215. loopMode,
  49216. /**Specifies if blending should be enabled */
  49217. enableBlending) {
  49218. this.name = name;
  49219. this.targetProperty = targetProperty;
  49220. this.framePerSecond = framePerSecond;
  49221. this.dataType = dataType;
  49222. this.loopMode = loopMode;
  49223. this.enableBlending = enableBlending;
  49224. /**
  49225. * @hidden Internal use only
  49226. */
  49227. this._runtimeAnimations = new Array();
  49228. /**
  49229. * The set of event that will be linked to this animation
  49230. */
  49231. this._events = new Array();
  49232. /**
  49233. * Stores the blending speed of the animation
  49234. */
  49235. this.blendingSpeed = 0.01;
  49236. /**
  49237. * Stores the animation ranges for the animation
  49238. */
  49239. this._ranges = {};
  49240. this.targetPropertyPath = targetProperty.split(".");
  49241. this.dataType = dataType;
  49242. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49243. }
  49244. /**
  49245. * @hidden Internal use
  49246. */
  49247. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49248. var dataType = undefined;
  49249. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49250. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49251. }
  49252. else if (from instanceof BABYLON.Quaternion) {
  49253. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49254. }
  49255. else if (from instanceof BABYLON.Vector3) {
  49256. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49257. }
  49258. else if (from instanceof BABYLON.Vector2) {
  49259. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49260. }
  49261. else if (from instanceof BABYLON.Color3) {
  49262. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49263. }
  49264. else if (from instanceof BABYLON.Size) {
  49265. dataType = Animation.ANIMATIONTYPE_SIZE;
  49266. }
  49267. if (dataType == undefined) {
  49268. return null;
  49269. }
  49270. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49271. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49272. animation.setKeys(keys);
  49273. if (easingFunction !== undefined) {
  49274. animation.setEasingFunction(easingFunction);
  49275. }
  49276. return animation;
  49277. };
  49278. /**
  49279. * Sets up an animation
  49280. * @param property The property to animate
  49281. * @param animationType The animation type to apply
  49282. * @param framePerSecond The frames per second of the animation
  49283. * @param easingFunction The easing function used in the animation
  49284. * @returns The created animation
  49285. */
  49286. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49287. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49288. animation.setEasingFunction(easingFunction);
  49289. return animation;
  49290. };
  49291. /**
  49292. * Create and start an animation on a node
  49293. * @param name defines the name of the global animation that will be run on all nodes
  49294. * @param node defines the root node where the animation will take place
  49295. * @param targetProperty defines property to animate
  49296. * @param framePerSecond defines the number of frame per second yo use
  49297. * @param totalFrame defines the number of frames in total
  49298. * @param from defines the initial value
  49299. * @param to defines the final value
  49300. * @param loopMode defines which loop mode you want to use (off by default)
  49301. * @param easingFunction defines the easing function to use (linear by default)
  49302. * @param onAnimationEnd defines the callback to call when animation end
  49303. * @returns the animatable created for this animation
  49304. */
  49305. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49306. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49307. if (!animation) {
  49308. return null;
  49309. }
  49310. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49311. };
  49312. /**
  49313. * Create and start an animation on a node and its descendants
  49314. * @param name defines the name of the global animation that will be run on all nodes
  49315. * @param node defines the root node where the animation will take place
  49316. * @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
  49317. * @param targetProperty defines property to animate
  49318. * @param framePerSecond defines the number of frame per second to use
  49319. * @param totalFrame defines the number of frames in total
  49320. * @param from defines the initial value
  49321. * @param to defines the final value
  49322. * @param loopMode defines which loop mode you want to use (off by default)
  49323. * @param easingFunction defines the easing function to use (linear by default)
  49324. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49325. * @returns the list of animatables created for all nodes
  49326. * @example https://www.babylonjs-playground.com/#MH0VLI
  49327. */
  49328. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49329. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49330. if (!animation) {
  49331. return null;
  49332. }
  49333. var scene = node.getScene();
  49334. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49335. };
  49336. /**
  49337. * Creates a new animation, merges it with the existing animations and starts it
  49338. * @param name Name of the animation
  49339. * @param node Node which contains the scene that begins the animations
  49340. * @param targetProperty Specifies which property to animate
  49341. * @param framePerSecond The frames per second of the animation
  49342. * @param totalFrame The total number of frames
  49343. * @param from The frame at the beginning of the animation
  49344. * @param to The frame at the end of the animation
  49345. * @param loopMode Specifies the loop mode of the animation
  49346. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49347. * @param onAnimationEnd Callback to run once the animation is complete
  49348. * @returns Nullable animation
  49349. */
  49350. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49351. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49352. if (!animation) {
  49353. return null;
  49354. }
  49355. node.animations.push(animation);
  49356. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49357. };
  49358. /**
  49359. * Transition property of an host to the target Value
  49360. * @param property The property to transition
  49361. * @param targetValue The target Value of the property
  49362. * @param host The object where the property to animate belongs
  49363. * @param scene Scene used to run the animation
  49364. * @param frameRate Framerate (in frame/s) to use
  49365. * @param transition The transition type we want to use
  49366. * @param duration The duration of the animation, in milliseconds
  49367. * @param onAnimationEnd Callback trigger at the end of the animation
  49368. * @returns Nullable animation
  49369. */
  49370. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49371. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49372. if (duration <= 0) {
  49373. host[property] = targetValue;
  49374. if (onAnimationEnd) {
  49375. onAnimationEnd();
  49376. }
  49377. return null;
  49378. }
  49379. var endFrame = frameRate * (duration / 1000);
  49380. transition.setKeys([{
  49381. frame: 0,
  49382. value: host[property].clone ? host[property].clone() : host[property]
  49383. },
  49384. {
  49385. frame: endFrame,
  49386. value: targetValue
  49387. }]);
  49388. if (!host.animations) {
  49389. host.animations = [];
  49390. }
  49391. host.animations.push(transition);
  49392. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49393. animation.onAnimationEnd = onAnimationEnd;
  49394. return animation;
  49395. };
  49396. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49397. /**
  49398. * Return the array of runtime animations currently using this animation
  49399. */
  49400. get: function () {
  49401. return this._runtimeAnimations;
  49402. },
  49403. enumerable: true,
  49404. configurable: true
  49405. });
  49406. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49407. /**
  49408. * Specifies if any of the runtime animations are currently running
  49409. */
  49410. get: function () {
  49411. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49412. var runtimeAnimation = _a[_i];
  49413. if (!runtimeAnimation.isStopped) {
  49414. return true;
  49415. }
  49416. }
  49417. return false;
  49418. },
  49419. enumerable: true,
  49420. configurable: true
  49421. });
  49422. // Methods
  49423. /**
  49424. * Converts the animation to a string
  49425. * @param fullDetails support for multiple levels of logging within scene loading
  49426. * @returns String form of the animation
  49427. */
  49428. Animation.prototype.toString = function (fullDetails) {
  49429. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49430. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49431. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49432. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49433. if (fullDetails) {
  49434. ret += ", Ranges: {";
  49435. var first = true;
  49436. for (var name in this._ranges) {
  49437. if (first) {
  49438. ret += ", ";
  49439. first = false;
  49440. }
  49441. ret += name;
  49442. }
  49443. ret += "}";
  49444. }
  49445. return ret;
  49446. };
  49447. /**
  49448. * Add an event to this animation
  49449. * @param event Event to add
  49450. */
  49451. Animation.prototype.addEvent = function (event) {
  49452. this._events.push(event);
  49453. };
  49454. /**
  49455. * Remove all events found at the given frame
  49456. * @param frame The frame to remove events from
  49457. */
  49458. Animation.prototype.removeEvents = function (frame) {
  49459. for (var index = 0; index < this._events.length; index++) {
  49460. if (this._events[index].frame === frame) {
  49461. this._events.splice(index, 1);
  49462. index--;
  49463. }
  49464. }
  49465. };
  49466. /**
  49467. * Retrieves all the events from the animation
  49468. * @returns Events from the animation
  49469. */
  49470. Animation.prototype.getEvents = function () {
  49471. return this._events;
  49472. };
  49473. /**
  49474. * Creates an animation range
  49475. * @param name Name of the animation range
  49476. * @param from Starting frame of the animation range
  49477. * @param to Ending frame of the animation
  49478. */
  49479. Animation.prototype.createRange = function (name, from, to) {
  49480. // check name not already in use; could happen for bones after serialized
  49481. if (!this._ranges[name]) {
  49482. this._ranges[name] = new AnimationRange(name, from, to);
  49483. }
  49484. };
  49485. /**
  49486. * Deletes an animation range by name
  49487. * @param name Name of the animation range to delete
  49488. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49489. */
  49490. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49491. if (deleteFrames === void 0) { deleteFrames = true; }
  49492. var range = this._ranges[name];
  49493. if (!range) {
  49494. return;
  49495. }
  49496. if (deleteFrames) {
  49497. var from = range.from;
  49498. var to = range.to;
  49499. // this loop MUST go high to low for multiple splices to work
  49500. for (var key = this._keys.length - 1; key >= 0; key--) {
  49501. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49502. this._keys.splice(key, 1);
  49503. }
  49504. }
  49505. }
  49506. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49507. };
  49508. /**
  49509. * Gets the animation range by name, or null if not defined
  49510. * @param name Name of the animation range
  49511. * @returns Nullable animation range
  49512. */
  49513. Animation.prototype.getRange = function (name) {
  49514. return this._ranges[name];
  49515. };
  49516. /**
  49517. * Gets the key frames from the animation
  49518. * @returns The key frames of the animation
  49519. */
  49520. Animation.prototype.getKeys = function () {
  49521. return this._keys;
  49522. };
  49523. /**
  49524. * Gets the highest frame rate of the animation
  49525. * @returns Highest frame rate of the animation
  49526. */
  49527. Animation.prototype.getHighestFrame = function () {
  49528. var ret = 0;
  49529. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49530. if (ret < this._keys[key].frame) {
  49531. ret = this._keys[key].frame;
  49532. }
  49533. }
  49534. return ret;
  49535. };
  49536. /**
  49537. * Gets the easing function of the animation
  49538. * @returns Easing function of the animation
  49539. */
  49540. Animation.prototype.getEasingFunction = function () {
  49541. return this._easingFunction;
  49542. };
  49543. /**
  49544. * Sets the easing function of the animation
  49545. * @param easingFunction A custom mathematical formula for animation
  49546. */
  49547. Animation.prototype.setEasingFunction = function (easingFunction) {
  49548. this._easingFunction = easingFunction;
  49549. };
  49550. /**
  49551. * Interpolates a scalar linearly
  49552. * @param startValue Start value of the animation curve
  49553. * @param endValue End value of the animation curve
  49554. * @param gradient Scalar amount to interpolate
  49555. * @returns Interpolated scalar value
  49556. */
  49557. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49558. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49559. };
  49560. /**
  49561. * Interpolates a scalar cubically
  49562. * @param startValue Start value of the animation curve
  49563. * @param outTangent End tangent of the animation
  49564. * @param endValue End value of the animation curve
  49565. * @param inTangent Start tangent of the animation curve
  49566. * @param gradient Scalar amount to interpolate
  49567. * @returns Interpolated scalar value
  49568. */
  49569. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49570. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49571. };
  49572. /**
  49573. * Interpolates a quaternion using a spherical linear interpolation
  49574. * @param startValue Start value of the animation curve
  49575. * @param endValue End value of the animation curve
  49576. * @param gradient Scalar amount to interpolate
  49577. * @returns Interpolated quaternion value
  49578. */
  49579. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49580. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49581. };
  49582. /**
  49583. * Interpolates a quaternion cubically
  49584. * @param startValue Start value of the animation curve
  49585. * @param outTangent End tangent of the animation curve
  49586. * @param endValue End value of the animation curve
  49587. * @param inTangent Start tangent of the animation curve
  49588. * @param gradient Scalar amount to interpolate
  49589. * @returns Interpolated quaternion value
  49590. */
  49591. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49592. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49593. };
  49594. /**
  49595. * Interpolates a Vector3 linearl
  49596. * @param startValue Start value of the animation curve
  49597. * @param endValue End value of the animation curve
  49598. * @param gradient Scalar amount to interpolate
  49599. * @returns Interpolated scalar value
  49600. */
  49601. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49602. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49603. };
  49604. /**
  49605. * Interpolates a Vector3 cubically
  49606. * @param startValue Start value of the animation curve
  49607. * @param outTangent End tangent of the animation
  49608. * @param endValue End value of the animation curve
  49609. * @param inTangent Start tangent of the animation curve
  49610. * @param gradient Scalar amount to interpolate
  49611. * @returns InterpolatedVector3 value
  49612. */
  49613. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49614. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49615. };
  49616. /**
  49617. * Interpolates a Vector2 linearly
  49618. * @param startValue Start value of the animation curve
  49619. * @param endValue End value of the animation curve
  49620. * @param gradient Scalar amount to interpolate
  49621. * @returns Interpolated Vector2 value
  49622. */
  49623. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49624. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49625. };
  49626. /**
  49627. * Interpolates a Vector2 cubically
  49628. * @param startValue Start value of the animation curve
  49629. * @param outTangent End tangent of the animation
  49630. * @param endValue End value of the animation curve
  49631. * @param inTangent Start tangent of the animation curve
  49632. * @param gradient Scalar amount to interpolate
  49633. * @returns Interpolated Vector2 value
  49634. */
  49635. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49636. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49637. };
  49638. /**
  49639. * Interpolates a size linearly
  49640. * @param startValue Start value of the animation curve
  49641. * @param endValue End value of the animation curve
  49642. * @param gradient Scalar amount to interpolate
  49643. * @returns Interpolated Size value
  49644. */
  49645. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49646. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49647. };
  49648. /**
  49649. * Interpolates a Color3 linearly
  49650. * @param startValue Start value of the animation curve
  49651. * @param endValue End value of the animation curve
  49652. * @param gradient Scalar amount to interpolate
  49653. * @returns Interpolated Color3 value
  49654. */
  49655. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49656. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49657. };
  49658. /**
  49659. * @hidden Internal use only
  49660. */
  49661. Animation.prototype._getKeyValue = function (value) {
  49662. if (typeof value === "function") {
  49663. return value();
  49664. }
  49665. return value;
  49666. };
  49667. /**
  49668. * @hidden Internal use only
  49669. */
  49670. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49671. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49672. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49673. }
  49674. var keys = this.getKeys();
  49675. // Try to get a hash to find the right key
  49676. 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));
  49677. if (keys[startKeyIndex].frame >= currentFrame) {
  49678. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49679. startKeyIndex--;
  49680. }
  49681. }
  49682. for (var key = startKeyIndex; key < keys.length; key++) {
  49683. var endKey = keys[key + 1];
  49684. if (endKey.frame >= currentFrame) {
  49685. var startKey = keys[key];
  49686. var startValue = this._getKeyValue(startKey.value);
  49687. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49688. return startValue;
  49689. }
  49690. var endValue = this._getKeyValue(endKey.value);
  49691. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49692. var frameDelta = endKey.frame - startKey.frame;
  49693. // gradient : percent of currentFrame between the frame inf and the frame sup
  49694. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49695. // check for easingFunction and correction of gradient
  49696. var easingFunction = this.getEasingFunction();
  49697. if (easingFunction != null) {
  49698. gradient = easingFunction.ease(gradient);
  49699. }
  49700. switch (this.dataType) {
  49701. // Float
  49702. case Animation.ANIMATIONTYPE_FLOAT:
  49703. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49704. switch (loopMode) {
  49705. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49706. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49707. return floatValue;
  49708. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49709. return offsetValue * repeatCount + floatValue;
  49710. }
  49711. break;
  49712. // Quaternion
  49713. case Animation.ANIMATIONTYPE_QUATERNION:
  49714. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49715. switch (loopMode) {
  49716. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49717. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49718. return quatValue;
  49719. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49720. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49721. }
  49722. return quatValue;
  49723. // Vector3
  49724. case Animation.ANIMATIONTYPE_VECTOR3:
  49725. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49726. switch (loopMode) {
  49727. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49728. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49729. return vec3Value;
  49730. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49731. return vec3Value.add(offsetValue.scale(repeatCount));
  49732. }
  49733. // Vector2
  49734. case Animation.ANIMATIONTYPE_VECTOR2:
  49735. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49736. switch (loopMode) {
  49737. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49738. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49739. return vec2Value;
  49740. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49741. return vec2Value.add(offsetValue.scale(repeatCount));
  49742. }
  49743. // Size
  49744. case Animation.ANIMATIONTYPE_SIZE:
  49745. switch (loopMode) {
  49746. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49747. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49748. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49749. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49750. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49751. }
  49752. // Color3
  49753. case Animation.ANIMATIONTYPE_COLOR3:
  49754. switch (loopMode) {
  49755. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49756. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49757. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49758. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49759. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49760. }
  49761. // Matrix
  49762. case Animation.ANIMATIONTYPE_MATRIX:
  49763. switch (loopMode) {
  49764. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49765. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49766. if (Animation.AllowMatricesInterpolation) {
  49767. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49768. }
  49769. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49770. return startValue;
  49771. }
  49772. default:
  49773. break;
  49774. }
  49775. break;
  49776. }
  49777. }
  49778. return this._getKeyValue(keys[keys.length - 1].value);
  49779. };
  49780. /**
  49781. * Defines the function to use to interpolate matrices
  49782. * @param startValue defines the start matrix
  49783. * @param endValue defines the end matrix
  49784. * @param gradient defines the gradient between both matrices
  49785. * @param result defines an optional target matrix where to store the interpolation
  49786. * @returns the interpolated matrix
  49787. */
  49788. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49789. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49790. if (result) {
  49791. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49792. return result;
  49793. }
  49794. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49795. }
  49796. if (result) {
  49797. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  49798. return result;
  49799. }
  49800. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49801. };
  49802. /**
  49803. * Makes a copy of the animation
  49804. * @returns Cloned animation
  49805. */
  49806. Animation.prototype.clone = function () {
  49807. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49808. clone.enableBlending = this.enableBlending;
  49809. clone.blendingSpeed = this.blendingSpeed;
  49810. if (this._keys) {
  49811. clone.setKeys(this._keys);
  49812. }
  49813. if (this._ranges) {
  49814. clone._ranges = {};
  49815. for (var name in this._ranges) {
  49816. var range = this._ranges[name];
  49817. if (!range) {
  49818. continue;
  49819. }
  49820. clone._ranges[name] = range.clone();
  49821. }
  49822. }
  49823. return clone;
  49824. };
  49825. /**
  49826. * Sets the key frames of the animation
  49827. * @param values The animation key frames to set
  49828. */
  49829. Animation.prototype.setKeys = function (values) {
  49830. this._keys = values.slice(0);
  49831. };
  49832. /**
  49833. * Serializes the animation to an object
  49834. * @returns Serialized object
  49835. */
  49836. Animation.prototype.serialize = function () {
  49837. var serializationObject = {};
  49838. serializationObject.name = this.name;
  49839. serializationObject.property = this.targetProperty;
  49840. serializationObject.framePerSecond = this.framePerSecond;
  49841. serializationObject.dataType = this.dataType;
  49842. serializationObject.loopBehavior = this.loopMode;
  49843. serializationObject.enableBlending = this.enableBlending;
  49844. serializationObject.blendingSpeed = this.blendingSpeed;
  49845. var dataType = this.dataType;
  49846. serializationObject.keys = [];
  49847. var keys = this.getKeys();
  49848. for (var index = 0; index < keys.length; index++) {
  49849. var animationKey = keys[index];
  49850. var key = {};
  49851. key.frame = animationKey.frame;
  49852. switch (dataType) {
  49853. case Animation.ANIMATIONTYPE_FLOAT:
  49854. key.values = [animationKey.value];
  49855. break;
  49856. case Animation.ANIMATIONTYPE_QUATERNION:
  49857. case Animation.ANIMATIONTYPE_MATRIX:
  49858. case Animation.ANIMATIONTYPE_VECTOR3:
  49859. case Animation.ANIMATIONTYPE_COLOR3:
  49860. key.values = animationKey.value.asArray();
  49861. break;
  49862. }
  49863. serializationObject.keys.push(key);
  49864. }
  49865. serializationObject.ranges = [];
  49866. for (var name in this._ranges) {
  49867. var source = this._ranges[name];
  49868. if (!source) {
  49869. continue;
  49870. }
  49871. var range = {};
  49872. range.name = name;
  49873. range.from = source.from;
  49874. range.to = source.to;
  49875. serializationObject.ranges.push(range);
  49876. }
  49877. return serializationObject;
  49878. };
  49879. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  49880. /**
  49881. * Get the float animation type
  49882. */
  49883. get: function () {
  49884. return Animation._ANIMATIONTYPE_FLOAT;
  49885. },
  49886. enumerable: true,
  49887. configurable: true
  49888. });
  49889. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  49890. /**
  49891. * Get the Vector3 animation type
  49892. */
  49893. get: function () {
  49894. return Animation._ANIMATIONTYPE_VECTOR3;
  49895. },
  49896. enumerable: true,
  49897. configurable: true
  49898. });
  49899. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  49900. /**
  49901. * Get the Vectpr2 animation type
  49902. */
  49903. get: function () {
  49904. return Animation._ANIMATIONTYPE_VECTOR2;
  49905. },
  49906. enumerable: true,
  49907. configurable: true
  49908. });
  49909. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  49910. /**
  49911. * Get the Size animation type
  49912. */
  49913. get: function () {
  49914. return Animation._ANIMATIONTYPE_SIZE;
  49915. },
  49916. enumerable: true,
  49917. configurable: true
  49918. });
  49919. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  49920. /**
  49921. * Get the Quaternion animation type
  49922. */
  49923. get: function () {
  49924. return Animation._ANIMATIONTYPE_QUATERNION;
  49925. },
  49926. enumerable: true,
  49927. configurable: true
  49928. });
  49929. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  49930. /**
  49931. * Get the Matrix animation type
  49932. */
  49933. get: function () {
  49934. return Animation._ANIMATIONTYPE_MATRIX;
  49935. },
  49936. enumerable: true,
  49937. configurable: true
  49938. });
  49939. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  49940. /**
  49941. * Get the Color3 animation type
  49942. */
  49943. get: function () {
  49944. return Animation._ANIMATIONTYPE_COLOR3;
  49945. },
  49946. enumerable: true,
  49947. configurable: true
  49948. });
  49949. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  49950. /**
  49951. * Get the Relative Loop Mode
  49952. */
  49953. get: function () {
  49954. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  49955. },
  49956. enumerable: true,
  49957. configurable: true
  49958. });
  49959. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  49960. /**
  49961. * Get the Cycle Loop Mode
  49962. */
  49963. get: function () {
  49964. return Animation._ANIMATIONLOOPMODE_CYCLE;
  49965. },
  49966. enumerable: true,
  49967. configurable: true
  49968. });
  49969. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  49970. /**
  49971. * Get the Constant Loop Mode
  49972. */
  49973. get: function () {
  49974. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  49975. },
  49976. enumerable: true,
  49977. configurable: true
  49978. });
  49979. /** @hidden */
  49980. Animation._UniversalLerp = function (left, right, amount) {
  49981. var constructor = left.constructor;
  49982. if (constructor.Lerp) { // Lerp supported
  49983. return constructor.Lerp(left, right, amount);
  49984. }
  49985. else if (constructor.Slerp) { // Slerp supported
  49986. return constructor.Slerp(left, right, amount);
  49987. }
  49988. else if (left.toFixed) { // Number
  49989. return left * (1.0 - amount) + amount * right;
  49990. }
  49991. else { // Blending not supported
  49992. return right;
  49993. }
  49994. };
  49995. /**
  49996. * Parses an animation object and creates an animation
  49997. * @param parsedAnimation Parsed animation object
  49998. * @returns Animation object
  49999. */
  50000. Animation.Parse = function (parsedAnimation) {
  50001. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50002. var dataType = parsedAnimation.dataType;
  50003. var keys = [];
  50004. var data;
  50005. var index;
  50006. if (parsedAnimation.enableBlending) {
  50007. animation.enableBlending = parsedAnimation.enableBlending;
  50008. }
  50009. if (parsedAnimation.blendingSpeed) {
  50010. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50011. }
  50012. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50013. var key = parsedAnimation.keys[index];
  50014. var inTangent;
  50015. var outTangent;
  50016. switch (dataType) {
  50017. case Animation.ANIMATIONTYPE_FLOAT:
  50018. data = key.values[0];
  50019. if (key.values.length >= 1) {
  50020. inTangent = key.values[1];
  50021. }
  50022. if (key.values.length >= 2) {
  50023. outTangent = key.values[2];
  50024. }
  50025. break;
  50026. case Animation.ANIMATIONTYPE_QUATERNION:
  50027. data = BABYLON.Quaternion.FromArray(key.values);
  50028. if (key.values.length >= 8) {
  50029. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50030. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50031. inTangent = _inTangent;
  50032. }
  50033. }
  50034. if (key.values.length >= 12) {
  50035. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50036. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50037. outTangent = _outTangent;
  50038. }
  50039. }
  50040. break;
  50041. case Animation.ANIMATIONTYPE_MATRIX:
  50042. data = BABYLON.Matrix.FromArray(key.values);
  50043. break;
  50044. case Animation.ANIMATIONTYPE_COLOR3:
  50045. data = BABYLON.Color3.FromArray(key.values);
  50046. break;
  50047. case Animation.ANIMATIONTYPE_VECTOR3:
  50048. default:
  50049. data = BABYLON.Vector3.FromArray(key.values);
  50050. break;
  50051. }
  50052. var keyData = {};
  50053. keyData.frame = key.frame;
  50054. keyData.value = data;
  50055. if (inTangent != undefined) {
  50056. keyData.inTangent = inTangent;
  50057. }
  50058. if (outTangent != undefined) {
  50059. keyData.outTangent = outTangent;
  50060. }
  50061. keys.push(keyData);
  50062. }
  50063. animation.setKeys(keys);
  50064. if (parsedAnimation.ranges) {
  50065. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50066. data = parsedAnimation.ranges[index];
  50067. animation.createRange(data.name, data.from, data.to);
  50068. }
  50069. }
  50070. return animation;
  50071. };
  50072. /**
  50073. * Appends the serialized animations from the source animations
  50074. * @param source Source containing the animations
  50075. * @param destination Target to store the animations
  50076. */
  50077. Animation.AppendSerializedAnimations = function (source, destination) {
  50078. if (source.animations) {
  50079. destination.animations = [];
  50080. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50081. var animation = source.animations[animationIndex];
  50082. destination.animations.push(animation.serialize());
  50083. }
  50084. }
  50085. };
  50086. /**
  50087. * Use matrix interpolation instead of using direct key value when animating matrices
  50088. */
  50089. Animation.AllowMatricesInterpolation = false;
  50090. /**
  50091. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50092. */
  50093. Animation.AllowMatrixDecomposeForInterpolation = true;
  50094. // Statics
  50095. /**
  50096. * Float animation type
  50097. */
  50098. Animation._ANIMATIONTYPE_FLOAT = 0;
  50099. /**
  50100. * Vector3 animation type
  50101. */
  50102. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50103. /**
  50104. * Quaternion animation type
  50105. */
  50106. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50107. /**
  50108. * Matrix animation type
  50109. */
  50110. Animation._ANIMATIONTYPE_MATRIX = 3;
  50111. /**
  50112. * Color3 animation type
  50113. */
  50114. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50115. /**
  50116. * Vector2 animation type
  50117. */
  50118. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50119. /**
  50120. * Size animation type
  50121. */
  50122. Animation._ANIMATIONTYPE_SIZE = 6;
  50123. /**
  50124. * Relative Loop Mode
  50125. */
  50126. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50127. /**
  50128. * Cycle Loop Mode
  50129. */
  50130. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50131. /**
  50132. * Constant Loop Mode
  50133. */
  50134. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50135. return Animation;
  50136. }());
  50137. BABYLON.Animation = Animation;
  50138. })(BABYLON || (BABYLON = {}));
  50139. //# sourceMappingURL=babylon.animation.js.map
  50140. var BABYLON;
  50141. (function (BABYLON) {
  50142. /**
  50143. * This class defines the direct association between an animation and a target
  50144. */
  50145. var TargetedAnimation = /** @class */ (function () {
  50146. function TargetedAnimation() {
  50147. }
  50148. return TargetedAnimation;
  50149. }());
  50150. BABYLON.TargetedAnimation = TargetedAnimation;
  50151. /**
  50152. * Use this class to create coordinated animations on multiple targets
  50153. */
  50154. var AnimationGroup = /** @class */ (function () {
  50155. function AnimationGroup(name, scene) {
  50156. if (scene === void 0) { scene = null; }
  50157. this.name = name;
  50158. this._targetedAnimations = new Array();
  50159. this._animatables = new Array();
  50160. this._from = Number.MAX_VALUE;
  50161. this._to = -Number.MAX_VALUE;
  50162. this._speedRatio = 1;
  50163. this.onAnimationEndObservable = new BABYLON.Observable();
  50164. /**
  50165. * This observable will notify when all animations have ended.
  50166. */
  50167. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50168. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50169. this._scene.animationGroups.push(this);
  50170. }
  50171. Object.defineProperty(AnimationGroup.prototype, "from", {
  50172. /**
  50173. * Gets the first frame
  50174. */
  50175. get: function () {
  50176. return this._from;
  50177. },
  50178. enumerable: true,
  50179. configurable: true
  50180. });
  50181. Object.defineProperty(AnimationGroup.prototype, "to", {
  50182. /**
  50183. * Gets the last frame
  50184. */
  50185. get: function () {
  50186. return this._to;
  50187. },
  50188. enumerable: true,
  50189. configurable: true
  50190. });
  50191. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50192. /**
  50193. * Define if the animations are started
  50194. */
  50195. get: function () {
  50196. return this._isStarted;
  50197. },
  50198. enumerable: true,
  50199. configurable: true
  50200. });
  50201. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50202. /**
  50203. * Gets or sets the speed ratio to use for all animations
  50204. */
  50205. get: function () {
  50206. return this._speedRatio;
  50207. },
  50208. /**
  50209. * Gets or sets the speed ratio to use for all animations
  50210. */
  50211. set: function (value) {
  50212. if (this._speedRatio === value) {
  50213. return;
  50214. }
  50215. this._speedRatio = value;
  50216. for (var index = 0; index < this._animatables.length; index++) {
  50217. var animatable = this._animatables[index];
  50218. animatable.speedRatio = this._speedRatio;
  50219. }
  50220. },
  50221. enumerable: true,
  50222. configurable: true
  50223. });
  50224. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50225. /**
  50226. * Gets the targeted animations for this animation group
  50227. */
  50228. get: function () {
  50229. return this._targetedAnimations;
  50230. },
  50231. enumerable: true,
  50232. configurable: true
  50233. });
  50234. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50235. /**
  50236. * returning the list of animatables controlled by this animation group.
  50237. */
  50238. get: function () {
  50239. return this._animatables;
  50240. },
  50241. enumerable: true,
  50242. configurable: true
  50243. });
  50244. /**
  50245. * Add an animation (with its target) in the group
  50246. * @param animation defines the animation we want to add
  50247. * @param target defines the target of the animation
  50248. * @returns the {BABYLON.TargetedAnimation} object
  50249. */
  50250. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50251. var targetedAnimation = {
  50252. animation: animation,
  50253. target: target
  50254. };
  50255. var keys = animation.getKeys();
  50256. if (this._from > keys[0].frame) {
  50257. this._from = keys[0].frame;
  50258. }
  50259. if (this._to < keys[keys.length - 1].frame) {
  50260. this._to = keys[keys.length - 1].frame;
  50261. }
  50262. this._targetedAnimations.push(targetedAnimation);
  50263. return targetedAnimation;
  50264. };
  50265. /**
  50266. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50267. * It can add constant keys at begin or end
  50268. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50269. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50270. */
  50271. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50272. if (beginFrame === void 0) { beginFrame = null; }
  50273. if (endFrame === void 0) { endFrame = null; }
  50274. if (beginFrame == null)
  50275. beginFrame = this._from;
  50276. if (endFrame == null)
  50277. endFrame = this._to;
  50278. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50279. var targetedAnimation = this._targetedAnimations[index];
  50280. var keys = targetedAnimation.animation.getKeys();
  50281. var startKey = keys[0];
  50282. var endKey = keys[keys.length - 1];
  50283. if (startKey.frame > beginFrame) {
  50284. var newKey = {
  50285. frame: beginFrame,
  50286. value: startKey.value,
  50287. inTangent: startKey.inTangent,
  50288. outTangent: startKey.outTangent,
  50289. interpolation: startKey.interpolation
  50290. };
  50291. keys.splice(0, 0, newKey);
  50292. }
  50293. if (endKey.frame < endFrame) {
  50294. var newKey = {
  50295. frame: endFrame,
  50296. value: endKey.value,
  50297. inTangent: endKey.outTangent,
  50298. outTangent: endKey.outTangent,
  50299. interpolation: endKey.interpolation
  50300. };
  50301. keys.push(newKey);
  50302. }
  50303. }
  50304. this._from = beginFrame;
  50305. this._to = endFrame;
  50306. return this;
  50307. };
  50308. /**
  50309. * Start all animations on given targets
  50310. * @param loop defines if animations must loop
  50311. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50312. * @param from defines the from key (optional)
  50313. * @param to defines the to key (optional)
  50314. * @returns the current animation group
  50315. */
  50316. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50317. var _this = this;
  50318. if (loop === void 0) { loop = false; }
  50319. if (speedRatio === void 0) { speedRatio = 1; }
  50320. if (this._isStarted || this._targetedAnimations.length === 0) {
  50321. return this;
  50322. }
  50323. var _loop_1 = function (targetedAnimation) {
  50324. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50325. animatable.onAnimationEnd = function () {
  50326. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50327. _this._checkAnimationGroupEnded(animatable);
  50328. };
  50329. this_1._animatables.push(animatable);
  50330. };
  50331. var this_1 = this;
  50332. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50333. var targetedAnimation = _a[_i];
  50334. _loop_1(targetedAnimation);
  50335. }
  50336. this._speedRatio = speedRatio;
  50337. this._isStarted = true;
  50338. return this;
  50339. };
  50340. /**
  50341. * Pause all animations
  50342. */
  50343. AnimationGroup.prototype.pause = function () {
  50344. if (!this._isStarted) {
  50345. return this;
  50346. }
  50347. for (var index = 0; index < this._animatables.length; index++) {
  50348. var animatable = this._animatables[index];
  50349. animatable.pause();
  50350. }
  50351. return this;
  50352. };
  50353. /**
  50354. * Play all animations to initial state
  50355. * This function will start() the animations if they were not started or will restart() them if they were paused
  50356. * @param loop defines if animations must loop
  50357. */
  50358. AnimationGroup.prototype.play = function (loop) {
  50359. // only if all animatables are ready and exist
  50360. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50361. if (loop !== undefined) {
  50362. for (var index = 0; index < this._animatables.length; index++) {
  50363. var animatable = this._animatables[index];
  50364. animatable.loopAnimation = loop;
  50365. }
  50366. }
  50367. this.restart();
  50368. }
  50369. else {
  50370. this.stop();
  50371. this.start(loop, this._speedRatio);
  50372. }
  50373. return this;
  50374. };
  50375. /**
  50376. * Reset all animations to initial state
  50377. */
  50378. AnimationGroup.prototype.reset = function () {
  50379. if (!this._isStarted) {
  50380. return this;
  50381. }
  50382. for (var index = 0; index < this._animatables.length; index++) {
  50383. var animatable = this._animatables[index];
  50384. animatable.reset();
  50385. }
  50386. return this;
  50387. };
  50388. /**
  50389. * Restart animations from key 0
  50390. */
  50391. AnimationGroup.prototype.restart = function () {
  50392. if (!this._isStarted) {
  50393. return this;
  50394. }
  50395. for (var index = 0; index < this._animatables.length; index++) {
  50396. var animatable = this._animatables[index];
  50397. animatable.restart();
  50398. }
  50399. return this;
  50400. };
  50401. /**
  50402. * Stop all animations
  50403. */
  50404. AnimationGroup.prototype.stop = function () {
  50405. if (!this._isStarted) {
  50406. return this;
  50407. }
  50408. var list = this._animatables.slice();
  50409. for (var index = 0; index < list.length; index++) {
  50410. list[index].stop();
  50411. }
  50412. this._isStarted = false;
  50413. return this;
  50414. };
  50415. /**
  50416. * Set animation weight for all animatables
  50417. * @param weight defines the weight to use
  50418. * @return the animationGroup
  50419. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50420. */
  50421. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50422. for (var index = 0; index < this._animatables.length; index++) {
  50423. var animatable = this._animatables[index];
  50424. animatable.weight = weight;
  50425. }
  50426. return this;
  50427. };
  50428. /**
  50429. * Synchronize and normalize all animatables with a source animatable
  50430. * @param root defines the root animatable to synchronize with
  50431. * @return the animationGroup
  50432. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50433. */
  50434. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50435. for (var index = 0; index < this._animatables.length; index++) {
  50436. var animatable = this._animatables[index];
  50437. animatable.syncWith(root);
  50438. }
  50439. return this;
  50440. };
  50441. /**
  50442. * Goes to a specific frame in this animation group
  50443. * @param frame the frame number to go to
  50444. * @return the animationGroup
  50445. */
  50446. AnimationGroup.prototype.goToFrame = function (frame) {
  50447. if (!this._isStarted) {
  50448. return this;
  50449. }
  50450. for (var index = 0; index < this._animatables.length; index++) {
  50451. var animatable = this._animatables[index];
  50452. animatable.goToFrame(frame);
  50453. }
  50454. return this;
  50455. };
  50456. /**
  50457. * Dispose all associated resources
  50458. */
  50459. AnimationGroup.prototype.dispose = function () {
  50460. this._targetedAnimations = [];
  50461. this._animatables = [];
  50462. var index = this._scene.animationGroups.indexOf(this);
  50463. if (index > -1) {
  50464. this._scene.animationGroups.splice(index, 1);
  50465. }
  50466. };
  50467. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50468. // animatable should be taken out of the array
  50469. var idx = this._animatables.indexOf(animatable);
  50470. if (idx > -1) {
  50471. this._animatables.splice(idx, 1);
  50472. }
  50473. // all animatables were removed? animation group ended!
  50474. if (this._animatables.length === 0) {
  50475. this._isStarted = false;
  50476. this.onAnimationGroupEndObservable.notifyObservers(this);
  50477. }
  50478. };
  50479. return AnimationGroup;
  50480. }());
  50481. BABYLON.AnimationGroup = AnimationGroup;
  50482. })(BABYLON || (BABYLON = {}));
  50483. //# sourceMappingURL=babylon.animationGroup.js.map
  50484. var BABYLON;
  50485. (function (BABYLON) {
  50486. /**
  50487. * Defines a runtime animation
  50488. */
  50489. var RuntimeAnimation = /** @class */ (function () {
  50490. /**
  50491. * Create a new RuntimeAnimation object
  50492. * @param target defines the target of the animation
  50493. * @param animation defines the source animation object
  50494. * @param scene defines the hosting scene
  50495. * @param host defines the initiating Animatable
  50496. */
  50497. function RuntimeAnimation(target, animation, scene, host) {
  50498. var _this = this;
  50499. this._events = new Array();
  50500. /**
  50501. * The current frame of the runtime animation
  50502. */
  50503. this._currentFrame = 0;
  50504. /**
  50505. * The original value of the runtime animation
  50506. */
  50507. this._originalValue = new Array();
  50508. /**
  50509. * The offsets cache of the runtime animation
  50510. */
  50511. this._offsetsCache = {};
  50512. /**
  50513. * The high limits cache of the runtime animation
  50514. */
  50515. this._highLimitsCache = {};
  50516. /**
  50517. * Specifies if the runtime animation has been stopped
  50518. */
  50519. this._stopped = false;
  50520. /**
  50521. * The blending factor of the runtime animation
  50522. */
  50523. this._blendingFactor = 0;
  50524. /**
  50525. * The target path of the runtime animation
  50526. */
  50527. this._targetPath = "";
  50528. /**
  50529. * The weight of the runtime animation
  50530. */
  50531. this._weight = 1.0;
  50532. /**
  50533. * The ratio offset of the runtime animation
  50534. */
  50535. this._ratioOffset = 0;
  50536. /**
  50537. * The previous delay of the runtime animation
  50538. */
  50539. this._previousDelay = 0;
  50540. /**
  50541. * The previous ratio of the runtime animation
  50542. */
  50543. this._previousRatio = 0;
  50544. this._animation = animation;
  50545. this._target = target;
  50546. this._scene = scene;
  50547. this._host = host;
  50548. animation._runtimeAnimations.push(this);
  50549. // Cloning events locally
  50550. var events = animation.getEvents();
  50551. if (events && events.length > 0) {
  50552. events.forEach(function (e) {
  50553. _this._events.push(e._clone());
  50554. });
  50555. }
  50556. }
  50557. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50558. /**
  50559. * Gets the current frame of the runtime animation
  50560. */
  50561. get: function () {
  50562. return this._currentFrame;
  50563. },
  50564. enumerable: true,
  50565. configurable: true
  50566. });
  50567. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50568. /**
  50569. * Gets the weight of the runtime animation
  50570. */
  50571. get: function () {
  50572. return this._weight;
  50573. },
  50574. enumerable: true,
  50575. configurable: true
  50576. });
  50577. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50578. /**
  50579. * Gets the current value of the runtime animation
  50580. */
  50581. get: function () {
  50582. return this._currentValue;
  50583. },
  50584. enumerable: true,
  50585. configurable: true
  50586. });
  50587. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50588. /**
  50589. * Gets the target path of the runtime animation
  50590. */
  50591. get: function () {
  50592. return this._targetPath;
  50593. },
  50594. enumerable: true,
  50595. configurable: true
  50596. });
  50597. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50598. /**
  50599. * Gets the actual target of the runtime animation
  50600. */
  50601. get: function () {
  50602. return this._activeTarget;
  50603. },
  50604. enumerable: true,
  50605. configurable: true
  50606. });
  50607. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50608. /**
  50609. * Gets the animation from the runtime animation
  50610. */
  50611. get: function () {
  50612. return this._animation;
  50613. },
  50614. enumerable: true,
  50615. configurable: true
  50616. });
  50617. /**
  50618. * Resets the runtime animation to the beginning
  50619. * @param restoreOriginal defines whether to restore the target property to the original value
  50620. */
  50621. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50622. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50623. if (restoreOriginal) {
  50624. if (this._target instanceof Array) {
  50625. var index = 0;
  50626. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50627. var target = _a[_i];
  50628. if (this._originalValue[index] !== undefined) {
  50629. this._setValue(target, this._originalValue[index], -1);
  50630. }
  50631. index++;
  50632. }
  50633. }
  50634. else {
  50635. if (this._originalValue[0] !== undefined) {
  50636. this._setValue(this._target, this._originalValue[0], -1);
  50637. }
  50638. }
  50639. }
  50640. this._offsetsCache = {};
  50641. this._highLimitsCache = {};
  50642. this._currentFrame = 0;
  50643. this._blendingFactor = 0;
  50644. this._originalValue = new Array();
  50645. // Events
  50646. for (var index = 0; index < this._events.length; index++) {
  50647. this._events[index].isDone = false;
  50648. }
  50649. };
  50650. /**
  50651. * Specifies if the runtime animation is stopped
  50652. * @returns Boolean specifying if the runtime animation is stopped
  50653. */
  50654. RuntimeAnimation.prototype.isStopped = function () {
  50655. return this._stopped;
  50656. };
  50657. /**
  50658. * Disposes of the runtime animation
  50659. */
  50660. RuntimeAnimation.prototype.dispose = function () {
  50661. var index = this._animation.runtimeAnimations.indexOf(this);
  50662. if (index > -1) {
  50663. this._animation.runtimeAnimations.splice(index, 1);
  50664. }
  50665. };
  50666. /**
  50667. * Interpolates the animation from the current frame
  50668. * @param currentFrame The frame to interpolate the animation to
  50669. * @param repeatCount The number of times that the animation should loop
  50670. * @param loopMode The type of looping mode to use
  50671. * @param offsetValue Animation offset value
  50672. * @param highLimitValue The high limit value
  50673. * @returns The interpolated value
  50674. */
  50675. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50676. this._currentFrame = currentFrame;
  50677. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50678. this._workValue = BABYLON.Matrix.Zero();
  50679. }
  50680. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50681. };
  50682. /**
  50683. * Apply the interpolated value to the target
  50684. * @param currentValue defines the value computed by the animation
  50685. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50686. */
  50687. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50688. if (weight === void 0) { weight = 1.0; }
  50689. if (this._target instanceof Array) {
  50690. var index = 0;
  50691. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50692. var target = _a[_i];
  50693. this._setValue(target, currentValue, weight, index);
  50694. index++;
  50695. }
  50696. }
  50697. else {
  50698. this._setValue(this._target, currentValue, weight);
  50699. }
  50700. };
  50701. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50702. if (targetIndex === void 0) { targetIndex = 0; }
  50703. // Set value
  50704. var path;
  50705. var destination;
  50706. var targetPropertyPath = this._animation.targetPropertyPath;
  50707. if (targetPropertyPath.length > 1) {
  50708. var property = target[targetPropertyPath[0]];
  50709. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50710. property = property[targetPropertyPath[index]];
  50711. }
  50712. path = targetPropertyPath[targetPropertyPath.length - 1];
  50713. destination = property;
  50714. }
  50715. else {
  50716. path = targetPropertyPath[0];
  50717. destination = target;
  50718. }
  50719. this._targetPath = path;
  50720. this._activeTarget = destination;
  50721. this._weight = weight;
  50722. if (this._originalValue[targetIndex] === undefined) {
  50723. var originalValue = void 0;
  50724. if (destination.getRestPose && path === "_matrix") { // For bones
  50725. originalValue = destination.getRestPose();
  50726. }
  50727. else {
  50728. originalValue = destination[path];
  50729. }
  50730. if (originalValue && originalValue.clone) {
  50731. this._originalValue[targetIndex] = originalValue.clone();
  50732. }
  50733. else {
  50734. this._originalValue[targetIndex] = originalValue;
  50735. }
  50736. }
  50737. // Blending
  50738. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50739. if (enableBlending && this._blendingFactor <= 1.0) {
  50740. if (!this._originalBlendValue) {
  50741. var originalValue = destination[path];
  50742. if (originalValue.clone) {
  50743. this._originalBlendValue = originalValue.clone();
  50744. }
  50745. else {
  50746. this._originalBlendValue = originalValue;
  50747. }
  50748. }
  50749. if (this._originalBlendValue.m) { // Matrix
  50750. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50751. if (this._currentValue) {
  50752. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50753. }
  50754. else {
  50755. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50756. }
  50757. }
  50758. else {
  50759. if (this._currentValue) {
  50760. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50761. }
  50762. else {
  50763. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50764. }
  50765. }
  50766. }
  50767. else {
  50768. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50769. }
  50770. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50771. this._blendingFactor += blendingSpeed;
  50772. }
  50773. else {
  50774. this._currentValue = currentValue;
  50775. }
  50776. if (weight !== -1.0) {
  50777. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  50778. }
  50779. else {
  50780. destination[path] = this._currentValue;
  50781. }
  50782. if (target.markAsDirty) {
  50783. target.markAsDirty(this._animation.targetProperty);
  50784. }
  50785. };
  50786. /**
  50787. * Gets the loop pmode of the runtime animation
  50788. * @returns Loop Mode
  50789. */
  50790. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50791. if (this._target && this._target.animationPropertiesOverride) {
  50792. return this._target.animationPropertiesOverride.loopMode;
  50793. }
  50794. return this._animation.loopMode;
  50795. };
  50796. /**
  50797. * Move the current animation to a given frame
  50798. * @param frame defines the frame to move to
  50799. */
  50800. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50801. var keys = this._animation.getKeys();
  50802. if (frame < keys[0].frame) {
  50803. frame = keys[0].frame;
  50804. }
  50805. else if (frame > keys[keys.length - 1].frame) {
  50806. frame = keys[keys.length - 1].frame;
  50807. }
  50808. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50809. this.setValue(currentValue, -1);
  50810. };
  50811. /**
  50812. * @hidden Internal use only
  50813. */
  50814. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50815. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50816. this._ratioOffset = this._previousRatio - newRatio;
  50817. };
  50818. /**
  50819. * Execute the current animation
  50820. * @param delay defines the delay to add to the current frame
  50821. * @param from defines the lower bound of the animation range
  50822. * @param to defines the upper bound of the animation range
  50823. * @param loop defines if the current animation must loop
  50824. * @param speedRatio defines the current speed ratio
  50825. * @param weight defines the weight of the animation (default is -1 so no weight)
  50826. * @returns a boolean indicating if the animation has ended
  50827. */
  50828. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  50829. if (weight === void 0) { weight = -1.0; }
  50830. var targetPropertyPath = this._animation.targetPropertyPath;
  50831. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  50832. this._stopped = true;
  50833. return false;
  50834. }
  50835. var keys = this._animation.getKeys();
  50836. // Return immediately if there is only one key frame.
  50837. if (keys.length === 1) {
  50838. this.setValue(keys[0].value, weight);
  50839. return !loop;
  50840. }
  50841. var returnValue = true;
  50842. // Adding a start key at frame 0 if missing
  50843. if (keys[0].frame !== 0) {
  50844. var newKey = { frame: 0, value: keys[0].value };
  50845. keys.splice(0, 0, newKey);
  50846. }
  50847. // Check limits
  50848. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  50849. from = keys[0].frame;
  50850. }
  50851. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  50852. to = keys[keys.length - 1].frame;
  50853. }
  50854. //to and from cannot be the same key
  50855. if (from === to) {
  50856. if (from > keys[0].frame) {
  50857. from--;
  50858. }
  50859. else if (to < keys[keys.length - 1].frame) {
  50860. to++;
  50861. }
  50862. }
  50863. // Compute ratio
  50864. var range = to - from;
  50865. var offsetValue;
  50866. // ratio represents the frame delta between from and to
  50867. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  50868. var highLimitValue = 0;
  50869. this._previousDelay = delay;
  50870. this._previousRatio = ratio;
  50871. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  50872. returnValue = false;
  50873. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  50874. }
  50875. else {
  50876. // Get max value if required
  50877. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  50878. var keyOffset = to.toString() + from.toString();
  50879. if (!this._offsetsCache[keyOffset]) {
  50880. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50881. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50882. switch (this._animation.dataType) {
  50883. // Float
  50884. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50885. this._offsetsCache[keyOffset] = toValue - fromValue;
  50886. break;
  50887. // Quaternion
  50888. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50889. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50890. break;
  50891. // Vector3
  50892. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50893. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50894. // Vector2
  50895. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50896. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50897. // Size
  50898. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50899. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50900. // Color3
  50901. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50902. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50903. default:
  50904. break;
  50905. }
  50906. this._highLimitsCache[keyOffset] = toValue;
  50907. }
  50908. highLimitValue = this._highLimitsCache[keyOffset];
  50909. offsetValue = this._offsetsCache[keyOffset];
  50910. }
  50911. }
  50912. if (offsetValue === undefined) {
  50913. switch (this._animation.dataType) {
  50914. // Float
  50915. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50916. offsetValue = 0;
  50917. break;
  50918. // Quaternion
  50919. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50920. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  50921. break;
  50922. // Vector3
  50923. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50924. offsetValue = BABYLON.Vector3.Zero();
  50925. break;
  50926. // Vector2
  50927. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50928. offsetValue = BABYLON.Vector2.Zero();
  50929. break;
  50930. // Size
  50931. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50932. offsetValue = BABYLON.Size.Zero();
  50933. break;
  50934. // Color3
  50935. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50936. offsetValue = BABYLON.Color3.Black();
  50937. }
  50938. }
  50939. // Compute value
  50940. var repeatCount = (ratio / range) >> 0;
  50941. var currentFrame = returnValue ? from + ratio % range : to;
  50942. // Need to normalize?
  50943. if (this._host && this._host.syncRoot) {
  50944. var syncRoot = this._host.syncRoot;
  50945. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  50946. currentFrame = from + (to - from) * hostNormalizedFrame;
  50947. }
  50948. // Reset events if looping
  50949. var events = this._events;
  50950. if (range > 0 && this.currentFrame > currentFrame ||
  50951. range < 0 && this.currentFrame < currentFrame) {
  50952. // Need to reset animation events
  50953. for (var index = 0; index < events.length; index++) {
  50954. if (!events[index].onlyOnce) {
  50955. // reset event, the animation is looping
  50956. events[index].isDone = false;
  50957. }
  50958. }
  50959. }
  50960. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  50961. // Set value
  50962. this.setValue(currentValue, weight);
  50963. // Check events
  50964. for (var index = 0; index < events.length; index++) {
  50965. // Make sure current frame has passed event frame and that event frame is within the current range
  50966. // Also, handle both forward and reverse animations
  50967. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  50968. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  50969. var event = events[index];
  50970. if (!event.isDone) {
  50971. // If event should be done only once, remove it.
  50972. if (event.onlyOnce) {
  50973. events.splice(index, 1);
  50974. index--;
  50975. }
  50976. event.isDone = true;
  50977. event.action();
  50978. } // Don't do anything if the event has already be done.
  50979. }
  50980. }
  50981. if (!returnValue) {
  50982. this._stopped = true;
  50983. }
  50984. return returnValue;
  50985. };
  50986. return RuntimeAnimation;
  50987. }());
  50988. BABYLON.RuntimeAnimation = RuntimeAnimation;
  50989. })(BABYLON || (BABYLON = {}));
  50990. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  50991. var BABYLON;
  50992. (function (BABYLON) {
  50993. /**
  50994. * Class used to store an actual running animation
  50995. */
  50996. var Animatable = /** @class */ (function () {
  50997. /**
  50998. * Creates a new Animatable
  50999. * @param scene defines the hosting scene
  51000. * @param target defines the target object
  51001. * @param fromFrame defines the starting frame number (default is 0)
  51002. * @param toFrame defines the ending frame number (default is 100)
  51003. * @param loopAnimation defines if the animation must loop (default is false)
  51004. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51005. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51006. * @param animations defines a group of animation to add to the new Animatable
  51007. */
  51008. function Animatable(scene,
  51009. /** defines the target object */
  51010. target,
  51011. /** defines the starting frame number (default is 0) */
  51012. fromFrame,
  51013. /** defines the ending frame number (default is 100) */
  51014. toFrame,
  51015. /** defines if the animation must loop (default is false) */
  51016. loopAnimation, speedRatio,
  51017. /** defines a callback to call when animation ends if it is not looping */
  51018. onAnimationEnd, animations) {
  51019. if (fromFrame === void 0) { fromFrame = 0; }
  51020. if (toFrame === void 0) { toFrame = 100; }
  51021. if (loopAnimation === void 0) { loopAnimation = false; }
  51022. if (speedRatio === void 0) { speedRatio = 1.0; }
  51023. this.target = target;
  51024. this.fromFrame = fromFrame;
  51025. this.toFrame = toFrame;
  51026. this.loopAnimation = loopAnimation;
  51027. this.onAnimationEnd = onAnimationEnd;
  51028. this._localDelayOffset = null;
  51029. this._pausedDelay = null;
  51030. this._runtimeAnimations = new Array();
  51031. this._paused = false;
  51032. this._speedRatio = 1;
  51033. this._weight = -1.0;
  51034. /**
  51035. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51036. * This will only apply for non looping animation (default is true)
  51037. */
  51038. this.disposeOnEnd = true;
  51039. /**
  51040. * Gets a boolean indicating if the animation has started
  51041. */
  51042. this.animationStarted = false;
  51043. /**
  51044. * Observer raised when the animation ends
  51045. */
  51046. this.onAnimationEndObservable = new BABYLON.Observable();
  51047. this._scene = scene;
  51048. if (animations) {
  51049. this.appendAnimations(target, animations);
  51050. }
  51051. this._speedRatio = speedRatio;
  51052. scene._activeAnimatables.push(this);
  51053. }
  51054. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51055. /**
  51056. * Gets the root Animatable used to synchronize and normalize animations
  51057. */
  51058. get: function () {
  51059. return this._syncRoot;
  51060. },
  51061. enumerable: true,
  51062. configurable: true
  51063. });
  51064. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51065. /**
  51066. * Gets the current frame of the first RuntimeAnimation
  51067. * Used to synchronize Animatables
  51068. */
  51069. get: function () {
  51070. if (this._runtimeAnimations.length === 0) {
  51071. return 0;
  51072. }
  51073. return this._runtimeAnimations[0].currentFrame;
  51074. },
  51075. enumerable: true,
  51076. configurable: true
  51077. });
  51078. Object.defineProperty(Animatable.prototype, "weight", {
  51079. /**
  51080. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51081. */
  51082. get: function () {
  51083. return this._weight;
  51084. },
  51085. set: function (value) {
  51086. if (value === -1) { // -1 is ok and means no weight
  51087. this._weight = -1;
  51088. return;
  51089. }
  51090. // Else weight must be in [0, 1] range
  51091. this._weight = Math.min(Math.max(value, 0), 1.0);
  51092. },
  51093. enumerable: true,
  51094. configurable: true
  51095. });
  51096. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51097. /**
  51098. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51099. */
  51100. get: function () {
  51101. return this._speedRatio;
  51102. },
  51103. set: function (value) {
  51104. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51105. var animation = this._runtimeAnimations[index];
  51106. animation._prepareForSpeedRatioChange(value);
  51107. }
  51108. this._speedRatio = value;
  51109. },
  51110. enumerable: true,
  51111. configurable: true
  51112. });
  51113. // Methods
  51114. /**
  51115. * Synchronize and normalize current Animatable with a source Animatable
  51116. * This is useful when using animation weights and when animations are not of the same length
  51117. * @param root defines the root Animatable to synchronize with
  51118. * @returns the current Animatable
  51119. */
  51120. Animatable.prototype.syncWith = function (root) {
  51121. this._syncRoot = root;
  51122. if (root) {
  51123. // Make sure this animatable will animate after the root
  51124. var index = this._scene._activeAnimatables.indexOf(this);
  51125. if (index > -1) {
  51126. this._scene._activeAnimatables.splice(index, 1);
  51127. this._scene._activeAnimatables.push(this);
  51128. }
  51129. }
  51130. return this;
  51131. };
  51132. /**
  51133. * Gets the list of runtime animations
  51134. * @returns an array of RuntimeAnimation
  51135. */
  51136. Animatable.prototype.getAnimations = function () {
  51137. return this._runtimeAnimations;
  51138. };
  51139. /**
  51140. * Adds more animations to the current animatable
  51141. * @param target defines the target of the animations
  51142. * @param animations defines the new animations to add
  51143. */
  51144. Animatable.prototype.appendAnimations = function (target, animations) {
  51145. for (var index = 0; index < animations.length; index++) {
  51146. var animation = animations[index];
  51147. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51148. }
  51149. };
  51150. /**
  51151. * Gets the source animation for a specific property
  51152. * @param property defines the propertyu to look for
  51153. * @returns null or the source animation for the given property
  51154. */
  51155. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51156. var runtimeAnimations = this._runtimeAnimations;
  51157. for (var index = 0; index < runtimeAnimations.length; index++) {
  51158. if (runtimeAnimations[index].animation.targetProperty === property) {
  51159. return runtimeAnimations[index].animation;
  51160. }
  51161. }
  51162. return null;
  51163. };
  51164. /**
  51165. * Gets the runtime animation for a specific property
  51166. * @param property defines the propertyu to look for
  51167. * @returns null or the runtime animation for the given property
  51168. */
  51169. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51170. var runtimeAnimations = this._runtimeAnimations;
  51171. for (var index = 0; index < runtimeAnimations.length; index++) {
  51172. if (runtimeAnimations[index].animation.targetProperty === property) {
  51173. return runtimeAnimations[index];
  51174. }
  51175. }
  51176. return null;
  51177. };
  51178. /**
  51179. * Resets the animatable to its original state
  51180. */
  51181. Animatable.prototype.reset = function () {
  51182. var runtimeAnimations = this._runtimeAnimations;
  51183. for (var index = 0; index < runtimeAnimations.length; index++) {
  51184. runtimeAnimations[index].reset(true);
  51185. }
  51186. this._localDelayOffset = null;
  51187. this._pausedDelay = null;
  51188. };
  51189. /**
  51190. * Allows the animatable to blend with current running animations
  51191. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51192. * @param blendingSpeed defines the blending speed to use
  51193. */
  51194. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51195. var runtimeAnimations = this._runtimeAnimations;
  51196. for (var index = 0; index < runtimeAnimations.length; index++) {
  51197. runtimeAnimations[index].animation.enableBlending = true;
  51198. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51199. }
  51200. };
  51201. /**
  51202. * Disable animation blending
  51203. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51204. */
  51205. Animatable.prototype.disableBlending = function () {
  51206. var runtimeAnimations = this._runtimeAnimations;
  51207. for (var index = 0; index < runtimeAnimations.length; index++) {
  51208. runtimeAnimations[index].animation.enableBlending = false;
  51209. }
  51210. };
  51211. /**
  51212. * Jump directly to a given frame
  51213. * @param frame defines the frame to jump to
  51214. */
  51215. Animatable.prototype.goToFrame = function (frame) {
  51216. var runtimeAnimations = this._runtimeAnimations;
  51217. if (runtimeAnimations[0]) {
  51218. var fps = runtimeAnimations[0].animation.framePerSecond;
  51219. var currentFrame = runtimeAnimations[0].currentFrame;
  51220. var adjustTime = frame - currentFrame;
  51221. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51222. if (this._localDelayOffset === null) {
  51223. this._localDelayOffset = 0;
  51224. }
  51225. this._localDelayOffset -= delay;
  51226. }
  51227. for (var index = 0; index < runtimeAnimations.length; index++) {
  51228. runtimeAnimations[index].goToFrame(frame);
  51229. }
  51230. };
  51231. /**
  51232. * Pause the animation
  51233. */
  51234. Animatable.prototype.pause = function () {
  51235. if (this._paused) {
  51236. return;
  51237. }
  51238. this._paused = true;
  51239. };
  51240. /**
  51241. * Restart the animation
  51242. */
  51243. Animatable.prototype.restart = function () {
  51244. this._paused = false;
  51245. };
  51246. Animatable.prototype._raiseOnAnimationEnd = function () {
  51247. if (this.onAnimationEnd) {
  51248. this.onAnimationEnd();
  51249. }
  51250. this.onAnimationEndObservable.notifyObservers(this);
  51251. };
  51252. /**
  51253. * Stop and delete the current animation
  51254. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51255. * @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)
  51256. */
  51257. Animatable.prototype.stop = function (animationName, targetMask) {
  51258. if (animationName || targetMask) {
  51259. var idx = this._scene._activeAnimatables.indexOf(this);
  51260. if (idx > -1) {
  51261. var runtimeAnimations = this._runtimeAnimations;
  51262. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51263. var runtimeAnimation = runtimeAnimations[index];
  51264. if (animationName && runtimeAnimation.animation.name != animationName) {
  51265. continue;
  51266. }
  51267. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51268. continue;
  51269. }
  51270. runtimeAnimation.dispose();
  51271. runtimeAnimations.splice(index, 1);
  51272. }
  51273. if (runtimeAnimations.length == 0) {
  51274. this._scene._activeAnimatables.splice(idx, 1);
  51275. this._raiseOnAnimationEnd();
  51276. }
  51277. }
  51278. }
  51279. else {
  51280. var index = this._scene._activeAnimatables.indexOf(this);
  51281. if (index > -1) {
  51282. this._scene._activeAnimatables.splice(index, 1);
  51283. var runtimeAnimations = this._runtimeAnimations;
  51284. for (var index = 0; index < runtimeAnimations.length; index++) {
  51285. runtimeAnimations[index].dispose();
  51286. }
  51287. this._raiseOnAnimationEnd();
  51288. }
  51289. }
  51290. };
  51291. /**
  51292. * Wait asynchronously for the animation to end
  51293. * @returns a promise which will be fullfilled when the animation ends
  51294. */
  51295. Animatable.prototype.waitAsync = function () {
  51296. var _this = this;
  51297. return new Promise(function (resolve, reject) {
  51298. _this.onAnimationEndObservable.add(function () {
  51299. resolve(_this);
  51300. }, undefined, undefined, _this, true);
  51301. });
  51302. };
  51303. /** @hidden */
  51304. Animatable.prototype._animate = function (delay) {
  51305. if (this._paused) {
  51306. this.animationStarted = false;
  51307. if (this._pausedDelay === null) {
  51308. this._pausedDelay = delay;
  51309. }
  51310. return true;
  51311. }
  51312. if (this._localDelayOffset === null) {
  51313. this._localDelayOffset = delay;
  51314. this._pausedDelay = null;
  51315. }
  51316. else if (this._pausedDelay !== null) {
  51317. this._localDelayOffset += delay - this._pausedDelay;
  51318. this._pausedDelay = null;
  51319. }
  51320. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51321. return true;
  51322. }
  51323. // Animating
  51324. var running = false;
  51325. var runtimeAnimations = this._runtimeAnimations;
  51326. var index;
  51327. for (index = 0; index < runtimeAnimations.length; index++) {
  51328. var animation = runtimeAnimations[index];
  51329. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51330. running = running || isRunning;
  51331. }
  51332. this.animationStarted = running;
  51333. if (!running) {
  51334. if (this.disposeOnEnd) {
  51335. // Remove from active animatables
  51336. index = this._scene._activeAnimatables.indexOf(this);
  51337. this._scene._activeAnimatables.splice(index, 1);
  51338. // Dispose all runtime animations
  51339. for (index = 0; index < runtimeAnimations.length; index++) {
  51340. runtimeAnimations[index].dispose();
  51341. }
  51342. }
  51343. this._raiseOnAnimationEnd();
  51344. if (this.disposeOnEnd) {
  51345. this.onAnimationEnd = null;
  51346. this.onAnimationEndObservable.clear();
  51347. }
  51348. }
  51349. return running;
  51350. };
  51351. return Animatable;
  51352. }());
  51353. BABYLON.Animatable = Animatable;
  51354. })(BABYLON || (BABYLON = {}));
  51355. //# sourceMappingURL=babylon.animatable.js.map
  51356. var BABYLON;
  51357. (function (BABYLON) {
  51358. var EasingFunction = /** @class */ (function () {
  51359. function EasingFunction() {
  51360. // Properties
  51361. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51362. }
  51363. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51364. get: function () {
  51365. return EasingFunction._EASINGMODE_EASEIN;
  51366. },
  51367. enumerable: true,
  51368. configurable: true
  51369. });
  51370. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51371. get: function () {
  51372. return EasingFunction._EASINGMODE_EASEOUT;
  51373. },
  51374. enumerable: true,
  51375. configurable: true
  51376. });
  51377. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51378. get: function () {
  51379. return EasingFunction._EASINGMODE_EASEINOUT;
  51380. },
  51381. enumerable: true,
  51382. configurable: true
  51383. });
  51384. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51385. var n = Math.min(Math.max(easingMode, 0), 2);
  51386. this._easingMode = n;
  51387. };
  51388. EasingFunction.prototype.getEasingMode = function () {
  51389. return this._easingMode;
  51390. };
  51391. EasingFunction.prototype.easeInCore = function (gradient) {
  51392. throw new Error('You must implement this method');
  51393. };
  51394. EasingFunction.prototype.ease = function (gradient) {
  51395. switch (this._easingMode) {
  51396. case EasingFunction.EASINGMODE_EASEIN:
  51397. return this.easeInCore(gradient);
  51398. case EasingFunction.EASINGMODE_EASEOUT:
  51399. return (1 - this.easeInCore(1 - gradient));
  51400. }
  51401. if (gradient >= 0.5) {
  51402. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51403. }
  51404. return (this.easeInCore(gradient * 2) * 0.5);
  51405. };
  51406. //Statics
  51407. EasingFunction._EASINGMODE_EASEIN = 0;
  51408. EasingFunction._EASINGMODE_EASEOUT = 1;
  51409. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51410. return EasingFunction;
  51411. }());
  51412. BABYLON.EasingFunction = EasingFunction;
  51413. var CircleEase = /** @class */ (function (_super) {
  51414. __extends(CircleEase, _super);
  51415. function CircleEase() {
  51416. return _super !== null && _super.apply(this, arguments) || this;
  51417. }
  51418. CircleEase.prototype.easeInCore = function (gradient) {
  51419. gradient = Math.max(0, Math.min(1, gradient));
  51420. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51421. };
  51422. return CircleEase;
  51423. }(EasingFunction));
  51424. BABYLON.CircleEase = CircleEase;
  51425. var BackEase = /** @class */ (function (_super) {
  51426. __extends(BackEase, _super);
  51427. function BackEase(amplitude) {
  51428. if (amplitude === void 0) { amplitude = 1; }
  51429. var _this = _super.call(this) || this;
  51430. _this.amplitude = amplitude;
  51431. return _this;
  51432. }
  51433. BackEase.prototype.easeInCore = function (gradient) {
  51434. var num = Math.max(0, this.amplitude);
  51435. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51436. };
  51437. return BackEase;
  51438. }(EasingFunction));
  51439. BABYLON.BackEase = BackEase;
  51440. var BounceEase = /** @class */ (function (_super) {
  51441. __extends(BounceEase, _super);
  51442. function BounceEase(bounces, bounciness) {
  51443. if (bounces === void 0) { bounces = 3; }
  51444. if (bounciness === void 0) { bounciness = 2; }
  51445. var _this = _super.call(this) || this;
  51446. _this.bounces = bounces;
  51447. _this.bounciness = bounciness;
  51448. return _this;
  51449. }
  51450. BounceEase.prototype.easeInCore = function (gradient) {
  51451. var y = Math.max(0.0, this.bounces);
  51452. var bounciness = this.bounciness;
  51453. if (bounciness <= 1.0) {
  51454. bounciness = 1.001;
  51455. }
  51456. var num9 = Math.pow(bounciness, y);
  51457. var num5 = 1.0 - bounciness;
  51458. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51459. var num15 = gradient * num4;
  51460. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51461. var num3 = Math.floor(num65);
  51462. var num13 = num3 + 1.0;
  51463. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51464. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51465. var num7 = (num8 + num12) * 0.5;
  51466. var num6 = gradient - num7;
  51467. var num2 = num7 - num8;
  51468. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51469. };
  51470. return BounceEase;
  51471. }(EasingFunction));
  51472. BABYLON.BounceEase = BounceEase;
  51473. var CubicEase = /** @class */ (function (_super) {
  51474. __extends(CubicEase, _super);
  51475. function CubicEase() {
  51476. return _super !== null && _super.apply(this, arguments) || this;
  51477. }
  51478. CubicEase.prototype.easeInCore = function (gradient) {
  51479. return (gradient * gradient * gradient);
  51480. };
  51481. return CubicEase;
  51482. }(EasingFunction));
  51483. BABYLON.CubicEase = CubicEase;
  51484. var ElasticEase = /** @class */ (function (_super) {
  51485. __extends(ElasticEase, _super);
  51486. function ElasticEase(oscillations, springiness) {
  51487. if (oscillations === void 0) { oscillations = 3; }
  51488. if (springiness === void 0) { springiness = 3; }
  51489. var _this = _super.call(this) || this;
  51490. _this.oscillations = oscillations;
  51491. _this.springiness = springiness;
  51492. return _this;
  51493. }
  51494. ElasticEase.prototype.easeInCore = function (gradient) {
  51495. var num2;
  51496. var num3 = Math.max(0.0, this.oscillations);
  51497. var num = Math.max(0.0, this.springiness);
  51498. if (num == 0) {
  51499. num2 = gradient;
  51500. }
  51501. else {
  51502. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51503. }
  51504. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51505. };
  51506. return ElasticEase;
  51507. }(EasingFunction));
  51508. BABYLON.ElasticEase = ElasticEase;
  51509. var ExponentialEase = /** @class */ (function (_super) {
  51510. __extends(ExponentialEase, _super);
  51511. function ExponentialEase(exponent) {
  51512. if (exponent === void 0) { exponent = 2; }
  51513. var _this = _super.call(this) || this;
  51514. _this.exponent = exponent;
  51515. return _this;
  51516. }
  51517. ExponentialEase.prototype.easeInCore = function (gradient) {
  51518. if (this.exponent <= 0) {
  51519. return gradient;
  51520. }
  51521. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51522. };
  51523. return ExponentialEase;
  51524. }(EasingFunction));
  51525. BABYLON.ExponentialEase = ExponentialEase;
  51526. var PowerEase = /** @class */ (function (_super) {
  51527. __extends(PowerEase, _super);
  51528. function PowerEase(power) {
  51529. if (power === void 0) { power = 2; }
  51530. var _this = _super.call(this) || this;
  51531. _this.power = power;
  51532. return _this;
  51533. }
  51534. PowerEase.prototype.easeInCore = function (gradient) {
  51535. var y = Math.max(0.0, this.power);
  51536. return Math.pow(gradient, y);
  51537. };
  51538. return PowerEase;
  51539. }(EasingFunction));
  51540. BABYLON.PowerEase = PowerEase;
  51541. var QuadraticEase = /** @class */ (function (_super) {
  51542. __extends(QuadraticEase, _super);
  51543. function QuadraticEase() {
  51544. return _super !== null && _super.apply(this, arguments) || this;
  51545. }
  51546. QuadraticEase.prototype.easeInCore = function (gradient) {
  51547. return (gradient * gradient);
  51548. };
  51549. return QuadraticEase;
  51550. }(EasingFunction));
  51551. BABYLON.QuadraticEase = QuadraticEase;
  51552. var QuarticEase = /** @class */ (function (_super) {
  51553. __extends(QuarticEase, _super);
  51554. function QuarticEase() {
  51555. return _super !== null && _super.apply(this, arguments) || this;
  51556. }
  51557. QuarticEase.prototype.easeInCore = function (gradient) {
  51558. return (gradient * gradient * gradient * gradient);
  51559. };
  51560. return QuarticEase;
  51561. }(EasingFunction));
  51562. BABYLON.QuarticEase = QuarticEase;
  51563. var QuinticEase = /** @class */ (function (_super) {
  51564. __extends(QuinticEase, _super);
  51565. function QuinticEase() {
  51566. return _super !== null && _super.apply(this, arguments) || this;
  51567. }
  51568. QuinticEase.prototype.easeInCore = function (gradient) {
  51569. return (gradient * gradient * gradient * gradient * gradient);
  51570. };
  51571. return QuinticEase;
  51572. }(EasingFunction));
  51573. BABYLON.QuinticEase = QuinticEase;
  51574. var SineEase = /** @class */ (function (_super) {
  51575. __extends(SineEase, _super);
  51576. function SineEase() {
  51577. return _super !== null && _super.apply(this, arguments) || this;
  51578. }
  51579. SineEase.prototype.easeInCore = function (gradient) {
  51580. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51581. };
  51582. return SineEase;
  51583. }(EasingFunction));
  51584. BABYLON.SineEase = SineEase;
  51585. var BezierCurveEase = /** @class */ (function (_super) {
  51586. __extends(BezierCurveEase, _super);
  51587. function BezierCurveEase(x1, y1, x2, y2) {
  51588. if (x1 === void 0) { x1 = 0; }
  51589. if (y1 === void 0) { y1 = 0; }
  51590. if (x2 === void 0) { x2 = 1; }
  51591. if (y2 === void 0) { y2 = 1; }
  51592. var _this = _super.call(this) || this;
  51593. _this.x1 = x1;
  51594. _this.y1 = y1;
  51595. _this.x2 = x2;
  51596. _this.y2 = y2;
  51597. return _this;
  51598. }
  51599. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51600. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51601. };
  51602. return BezierCurveEase;
  51603. }(EasingFunction));
  51604. BABYLON.BezierCurveEase = BezierCurveEase;
  51605. })(BABYLON || (BABYLON = {}));
  51606. //# sourceMappingURL=babylon.easing.js.map
  51607. var BABYLON;
  51608. (function (BABYLON) {
  51609. /**
  51610. * A Condition applied to an Action
  51611. */
  51612. var Condition = /** @class */ (function () {
  51613. /**
  51614. * Creates a new Condition
  51615. * @param actionManager the manager of the action the condition is applied to
  51616. */
  51617. function Condition(actionManager) {
  51618. this._actionManager = actionManager;
  51619. }
  51620. /**
  51621. * Check if the current condition is valid
  51622. * @returns a boolean
  51623. */
  51624. Condition.prototype.isValid = function () {
  51625. return true;
  51626. };
  51627. /**
  51628. * Internal only
  51629. * @hidden
  51630. */
  51631. Condition.prototype._getProperty = function (propertyPath) {
  51632. return this._actionManager._getProperty(propertyPath);
  51633. };
  51634. /**
  51635. * Internal only
  51636. * @hidden
  51637. */
  51638. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51639. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51640. };
  51641. /**
  51642. * Serialize placeholder for child classes
  51643. * @returns the serialized object
  51644. */
  51645. Condition.prototype.serialize = function () {
  51646. };
  51647. /**
  51648. * Internal only
  51649. * @hidden
  51650. */
  51651. Condition.prototype._serialize = function (serializedCondition) {
  51652. return {
  51653. type: 2,
  51654. children: [],
  51655. name: serializedCondition.name,
  51656. properties: serializedCondition.properties
  51657. };
  51658. };
  51659. return Condition;
  51660. }());
  51661. BABYLON.Condition = Condition;
  51662. /**
  51663. * Defines specific conditional operators as extensions of Condition
  51664. */
  51665. var ValueCondition = /** @class */ (function (_super) {
  51666. __extends(ValueCondition, _super);
  51667. /**
  51668. * Creates a new ValueCondition
  51669. * @param actionManager manager for the action the condition applies to
  51670. * @param target for the action
  51671. * @param propertyPath path to specify the property of the target the conditional operator uses
  51672. * @param value the value compared by the conditional operator against the current value of the property
  51673. * @param operator the conditional operator, default ValueCondition.IsEqual
  51674. */
  51675. function ValueCondition(actionManager, target,
  51676. /** path to specify the property of the target the conditional operator uses */
  51677. propertyPath,
  51678. /** the value compared by the conditional operator against the current value of the property */
  51679. value,
  51680. /** the conditional operator, default ValueCondition.IsEqual */
  51681. operator) {
  51682. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51683. var _this = _super.call(this, actionManager) || this;
  51684. _this.propertyPath = propertyPath;
  51685. _this.value = value;
  51686. _this.operator = operator;
  51687. _this._target = target;
  51688. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51689. _this._property = _this._getProperty(_this.propertyPath);
  51690. return _this;
  51691. }
  51692. Object.defineProperty(ValueCondition, "IsEqual", {
  51693. /**
  51694. * returns the number for IsEqual
  51695. */
  51696. get: function () {
  51697. return ValueCondition._IsEqual;
  51698. },
  51699. enumerable: true,
  51700. configurable: true
  51701. });
  51702. Object.defineProperty(ValueCondition, "IsDifferent", {
  51703. /**
  51704. * Returns the number for IsDifferent
  51705. */
  51706. get: function () {
  51707. return ValueCondition._IsDifferent;
  51708. },
  51709. enumerable: true,
  51710. configurable: true
  51711. });
  51712. Object.defineProperty(ValueCondition, "IsGreater", {
  51713. /**
  51714. * Returns the number for IsGreater
  51715. */
  51716. get: function () {
  51717. return ValueCondition._IsGreater;
  51718. },
  51719. enumerable: true,
  51720. configurable: true
  51721. });
  51722. Object.defineProperty(ValueCondition, "IsLesser", {
  51723. /**
  51724. * Returns the number for IsLesser
  51725. */
  51726. get: function () {
  51727. return ValueCondition._IsLesser;
  51728. },
  51729. enumerable: true,
  51730. configurable: true
  51731. });
  51732. /**
  51733. * Compares the given value with the property value for the specified conditional operator
  51734. * @returns the result of the comparison
  51735. */
  51736. ValueCondition.prototype.isValid = function () {
  51737. switch (this.operator) {
  51738. case ValueCondition.IsGreater:
  51739. return this._effectiveTarget[this._property] > this.value;
  51740. case ValueCondition.IsLesser:
  51741. return this._effectiveTarget[this._property] < this.value;
  51742. case ValueCondition.IsEqual:
  51743. case ValueCondition.IsDifferent:
  51744. var check;
  51745. if (this.value.equals) {
  51746. check = this.value.equals(this._effectiveTarget[this._property]);
  51747. }
  51748. else {
  51749. check = this.value === this._effectiveTarget[this._property];
  51750. }
  51751. return this.operator === ValueCondition.IsEqual ? check : !check;
  51752. }
  51753. return false;
  51754. };
  51755. /**
  51756. * Serialize the ValueCondition into a JSON compatible object
  51757. * @returns serialization object
  51758. */
  51759. ValueCondition.prototype.serialize = function () {
  51760. return this._serialize({
  51761. name: "ValueCondition",
  51762. properties: [
  51763. BABYLON.Action._GetTargetProperty(this._target),
  51764. { name: "propertyPath", value: this.propertyPath },
  51765. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51766. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51767. ]
  51768. });
  51769. };
  51770. /**
  51771. * Gets the name of the conditional operator for the ValueCondition
  51772. * @param operator the conditional operator
  51773. * @returns the name
  51774. */
  51775. ValueCondition.GetOperatorName = function (operator) {
  51776. switch (operator) {
  51777. case ValueCondition._IsEqual: return "IsEqual";
  51778. case ValueCondition._IsDifferent: return "IsDifferent";
  51779. case ValueCondition._IsGreater: return "IsGreater";
  51780. case ValueCondition._IsLesser: return "IsLesser";
  51781. default: return "";
  51782. }
  51783. };
  51784. /**
  51785. * Internal only
  51786. * @hidden
  51787. */
  51788. ValueCondition._IsEqual = 0;
  51789. /**
  51790. * Internal only
  51791. * @hidden
  51792. */
  51793. ValueCondition._IsDifferent = 1;
  51794. /**
  51795. * Internal only
  51796. * @hidden
  51797. */
  51798. ValueCondition._IsGreater = 2;
  51799. /**
  51800. * Internal only
  51801. * @hidden
  51802. */
  51803. ValueCondition._IsLesser = 3;
  51804. return ValueCondition;
  51805. }(Condition));
  51806. BABYLON.ValueCondition = ValueCondition;
  51807. /**
  51808. * Defines a predicate condition as an extension of Condition
  51809. */
  51810. var PredicateCondition = /** @class */ (function (_super) {
  51811. __extends(PredicateCondition, _super);
  51812. /**
  51813. * Creates a new PredicateCondition
  51814. * @param actionManager manager for the action the condition applies to
  51815. * @param predicate defines the predicate function used to validate the condition
  51816. */
  51817. function PredicateCondition(actionManager,
  51818. /** defines the predicate function used to validate the condition */
  51819. predicate) {
  51820. var _this = _super.call(this, actionManager) || this;
  51821. _this.predicate = predicate;
  51822. return _this;
  51823. }
  51824. /**
  51825. * @returns the validity of the predicate condition
  51826. */
  51827. PredicateCondition.prototype.isValid = function () {
  51828. return this.predicate();
  51829. };
  51830. return PredicateCondition;
  51831. }(Condition));
  51832. BABYLON.PredicateCondition = PredicateCondition;
  51833. /**
  51834. * Defines a state condition as an extension of Condition
  51835. */
  51836. var StateCondition = /** @class */ (function (_super) {
  51837. __extends(StateCondition, _super);
  51838. /**
  51839. * Creates a new StateCondition
  51840. * @param actionManager manager for the action the condition applies to
  51841. * @param target of the condition
  51842. * @param value to compare with target state
  51843. */
  51844. function StateCondition(actionManager, target, value) {
  51845. var _this = _super.call(this, actionManager) || this;
  51846. _this.value = value;
  51847. _this._target = target;
  51848. return _this;
  51849. }
  51850. /**
  51851. * @returns the validity of the state
  51852. */
  51853. StateCondition.prototype.isValid = function () {
  51854. return this._target.state === this.value;
  51855. };
  51856. /**
  51857. * Serialize the StateCondition into a JSON compatible object
  51858. * @returns serialization object
  51859. */
  51860. StateCondition.prototype.serialize = function () {
  51861. return this._serialize({
  51862. name: "StateCondition",
  51863. properties: [
  51864. BABYLON.Action._GetTargetProperty(this._target),
  51865. { name: "value", value: this.value }
  51866. ]
  51867. });
  51868. };
  51869. return StateCondition;
  51870. }(Condition));
  51871. BABYLON.StateCondition = StateCondition;
  51872. })(BABYLON || (BABYLON = {}));
  51873. //# sourceMappingURL=babylon.condition.js.map
  51874. var BABYLON;
  51875. (function (BABYLON) {
  51876. /**
  51877. * The action to be carried out following a trigger
  51878. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51879. */
  51880. var Action = /** @class */ (function () {
  51881. /**
  51882. * Creates a new Action
  51883. * @param triggerOptions the trigger, with or without parameters, for the action
  51884. * @param condition an optional determinant of action
  51885. */
  51886. function Action(
  51887. /** the trigger, with or without parameters, for the action */
  51888. triggerOptions, condition) {
  51889. this.triggerOptions = triggerOptions;
  51890. /**
  51891. * An event triggered prior to action being executed.
  51892. */
  51893. this.onBeforeExecuteObservable = new BABYLON.Observable();
  51894. if (triggerOptions.parameter) {
  51895. this.trigger = triggerOptions.trigger;
  51896. this._triggerParameter = triggerOptions.parameter;
  51897. }
  51898. else {
  51899. this.trigger = triggerOptions;
  51900. }
  51901. this._nextActiveAction = this;
  51902. this._condition = condition;
  51903. }
  51904. /**
  51905. * Internal only
  51906. * @hidden
  51907. */
  51908. Action.prototype._prepare = function () {
  51909. };
  51910. /**
  51911. * Gets the trigger parameters
  51912. * @returns the trigger parameters
  51913. */
  51914. Action.prototype.getTriggerParameter = function () {
  51915. return this._triggerParameter;
  51916. };
  51917. /**
  51918. * Internal only - executes current action event
  51919. * @hidden
  51920. */
  51921. Action.prototype._executeCurrent = function (evt) {
  51922. if (this._nextActiveAction._condition) {
  51923. var condition = this._nextActiveAction._condition;
  51924. var currentRenderId = this._actionManager.getScene().getRenderId();
  51925. // We cache the current evaluation for the current frame
  51926. if (condition._evaluationId === currentRenderId) {
  51927. if (!condition._currentResult) {
  51928. return;
  51929. }
  51930. }
  51931. else {
  51932. condition._evaluationId = currentRenderId;
  51933. if (!condition.isValid()) {
  51934. condition._currentResult = false;
  51935. return;
  51936. }
  51937. condition._currentResult = true;
  51938. }
  51939. }
  51940. this.onBeforeExecuteObservable.notifyObservers(this);
  51941. this._nextActiveAction.execute(evt);
  51942. this.skipToNextActiveAction();
  51943. };
  51944. /**
  51945. * Execute placeholder for child classes
  51946. * @param evt optional action event
  51947. */
  51948. Action.prototype.execute = function (evt) {
  51949. };
  51950. /**
  51951. * Skips to next active action
  51952. */
  51953. Action.prototype.skipToNextActiveAction = function () {
  51954. if (this._nextActiveAction._child) {
  51955. if (!this._nextActiveAction._child._actionManager) {
  51956. this._nextActiveAction._child._actionManager = this._actionManager;
  51957. }
  51958. this._nextActiveAction = this._nextActiveAction._child;
  51959. }
  51960. else {
  51961. this._nextActiveAction = this;
  51962. }
  51963. };
  51964. /**
  51965. * Adds action to chain of actions, may be a DoNothingAction
  51966. * @param action defines the next action to execute
  51967. * @returns The action passed in
  51968. * @see https://www.babylonjs-playground.com/#1T30HR#0
  51969. */
  51970. Action.prototype.then = function (action) {
  51971. this._child = action;
  51972. action._actionManager = this._actionManager;
  51973. action._prepare();
  51974. return action;
  51975. };
  51976. /**
  51977. * Internal only
  51978. * @hidden
  51979. */
  51980. Action.prototype._getProperty = function (propertyPath) {
  51981. return this._actionManager._getProperty(propertyPath);
  51982. };
  51983. /**
  51984. * Internal only
  51985. * @hidden
  51986. */
  51987. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  51988. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51989. };
  51990. /**
  51991. * Serialize placeholder for child classes
  51992. * @param parent of child
  51993. * @returns the serialized object
  51994. */
  51995. Action.prototype.serialize = function (parent) {
  51996. };
  51997. /**
  51998. * Internal only called by serialize
  51999. * @hidden
  52000. */
  52001. Action.prototype._serialize = function (serializedAction, parent) {
  52002. var serializationObject = {
  52003. type: 1,
  52004. children: [],
  52005. name: serializedAction.name,
  52006. properties: serializedAction.properties || []
  52007. };
  52008. // Serialize child
  52009. if (this._child) {
  52010. this._child.serialize(serializationObject);
  52011. }
  52012. // Check if "this" has a condition
  52013. if (this._condition) {
  52014. var serializedCondition = this._condition.serialize();
  52015. serializedCondition.children.push(serializationObject);
  52016. if (parent) {
  52017. parent.children.push(serializedCondition);
  52018. }
  52019. return serializedCondition;
  52020. }
  52021. if (parent) {
  52022. parent.children.push(serializationObject);
  52023. }
  52024. return serializationObject;
  52025. };
  52026. /**
  52027. * Internal only
  52028. * @hidden
  52029. */
  52030. Action._SerializeValueAsString = function (value) {
  52031. if (typeof value === "number") {
  52032. return value.toString();
  52033. }
  52034. if (typeof value === "boolean") {
  52035. return value ? "true" : "false";
  52036. }
  52037. if (value instanceof BABYLON.Vector2) {
  52038. return value.x + ", " + value.y;
  52039. }
  52040. if (value instanceof BABYLON.Vector3) {
  52041. return value.x + ", " + value.y + ", " + value.z;
  52042. }
  52043. if (value instanceof BABYLON.Color3) {
  52044. return value.r + ", " + value.g + ", " + value.b;
  52045. }
  52046. if (value instanceof BABYLON.Color4) {
  52047. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52048. }
  52049. return value; // string
  52050. };
  52051. /**
  52052. * Internal only
  52053. * @hidden
  52054. */
  52055. Action._GetTargetProperty = function (target) {
  52056. return {
  52057. name: "target",
  52058. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52059. : target instanceof BABYLON.Light ? "LightProperties"
  52060. : target instanceof BABYLON.Camera ? "CameraProperties"
  52061. : "SceneProperties",
  52062. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52063. };
  52064. };
  52065. return Action;
  52066. }());
  52067. BABYLON.Action = Action;
  52068. })(BABYLON || (BABYLON = {}));
  52069. //# sourceMappingURL=babylon.action.js.map
  52070. var BABYLON;
  52071. (function (BABYLON) {
  52072. /**
  52073. * ActionEvent is the event being sent when an action is triggered.
  52074. */
  52075. var ActionEvent = /** @class */ (function () {
  52076. /**
  52077. * Creates a new ActionEvent
  52078. * @param source The mesh or sprite that triggered the action
  52079. * @param pointerX The X mouse cursor position at the time of the event
  52080. * @param pointerY The Y mouse cursor position at the time of the event
  52081. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52082. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52083. * @param additionalData additional data for the event
  52084. */
  52085. function ActionEvent(
  52086. /** The mesh or sprite that triggered the action */
  52087. source,
  52088. /** The X mouse cursor position at the time of the event */
  52089. pointerX,
  52090. /** The Y mouse cursor position at the time of the event */
  52091. pointerY,
  52092. /** The mesh that is currently pointed at (can be null) */
  52093. meshUnderPointer,
  52094. /** the original (browser) event that triggered the ActionEvent */
  52095. sourceEvent,
  52096. /** additional data for the event */
  52097. additionalData) {
  52098. this.source = source;
  52099. this.pointerX = pointerX;
  52100. this.pointerY = pointerY;
  52101. this.meshUnderPointer = meshUnderPointer;
  52102. this.sourceEvent = sourceEvent;
  52103. this.additionalData = additionalData;
  52104. }
  52105. /**
  52106. * Helper function to auto-create an ActionEvent from a source mesh.
  52107. * @param source The source mesh that triggered the event
  52108. * @param evt The original (browser) event
  52109. * @param additionalData additional data for the event
  52110. * @returns the new ActionEvent
  52111. */
  52112. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52113. var scene = source.getScene();
  52114. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52115. };
  52116. /**
  52117. * Helper function to auto-create an ActionEvent from a source sprite
  52118. * @param source The source sprite that triggered the event
  52119. * @param scene Scene associated with the sprite
  52120. * @param evt The original (browser) event
  52121. * @param additionalData additional data for the event
  52122. * @returns the new ActionEvent
  52123. */
  52124. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52125. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52126. };
  52127. /**
  52128. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52129. * @param scene the scene where the event occurred
  52130. * @param evt The original (browser) event
  52131. * @returns the new ActionEvent
  52132. */
  52133. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52134. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52135. };
  52136. /**
  52137. * Helper function to auto-create an ActionEvent from a primitive
  52138. * @param prim defines the target primitive
  52139. * @param pointerPos defines the pointer position
  52140. * @param evt The original (browser) event
  52141. * @param additionalData additional data for the event
  52142. * @returns the new ActionEvent
  52143. */
  52144. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52145. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52146. };
  52147. return ActionEvent;
  52148. }());
  52149. BABYLON.ActionEvent = ActionEvent;
  52150. /**
  52151. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52152. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52153. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52154. */
  52155. var ActionManager = /** @class */ (function () {
  52156. /**
  52157. * Creates a new action manager
  52158. * @param scene defines the hosting scene
  52159. */
  52160. function ActionManager(scene) {
  52161. // Members
  52162. /** Gets the list of actions */
  52163. this.actions = new Array();
  52164. /** Gets the cursor to use when hovering items */
  52165. this.hoverCursor = '';
  52166. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52167. scene.actionManagers.push(this);
  52168. }
  52169. Object.defineProperty(ActionManager, "NothingTrigger", {
  52170. /**
  52171. * Nothing
  52172. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52173. */
  52174. get: function () {
  52175. return ActionManager._NothingTrigger;
  52176. },
  52177. enumerable: true,
  52178. configurable: true
  52179. });
  52180. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52181. /**
  52182. * On pick
  52183. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52184. */
  52185. get: function () {
  52186. return ActionManager._OnPickTrigger;
  52187. },
  52188. enumerable: true,
  52189. configurable: true
  52190. });
  52191. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52192. /**
  52193. * On left pick
  52194. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52195. */
  52196. get: function () {
  52197. return ActionManager._OnLeftPickTrigger;
  52198. },
  52199. enumerable: true,
  52200. configurable: true
  52201. });
  52202. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52203. /**
  52204. * On right pick
  52205. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52206. */
  52207. get: function () {
  52208. return ActionManager._OnRightPickTrigger;
  52209. },
  52210. enumerable: true,
  52211. configurable: true
  52212. });
  52213. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52214. /**
  52215. * On center pick
  52216. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52217. */
  52218. get: function () {
  52219. return ActionManager._OnCenterPickTrigger;
  52220. },
  52221. enumerable: true,
  52222. configurable: true
  52223. });
  52224. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52225. /**
  52226. * On pick down
  52227. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52228. */
  52229. get: function () {
  52230. return ActionManager._OnPickDownTrigger;
  52231. },
  52232. enumerable: true,
  52233. configurable: true
  52234. });
  52235. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52236. /**
  52237. * On double pick
  52238. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52239. */
  52240. get: function () {
  52241. return ActionManager._OnDoublePickTrigger;
  52242. },
  52243. enumerable: true,
  52244. configurable: true
  52245. });
  52246. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52247. /**
  52248. * On pick up
  52249. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52250. */
  52251. get: function () {
  52252. return ActionManager._OnPickUpTrigger;
  52253. },
  52254. enumerable: true,
  52255. configurable: true
  52256. });
  52257. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52258. /**
  52259. * On pick out.
  52260. * This trigger will only be raised if you also declared a OnPickDown
  52261. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52262. */
  52263. get: function () {
  52264. return ActionManager._OnPickOutTrigger;
  52265. },
  52266. enumerable: true,
  52267. configurable: true
  52268. });
  52269. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52270. /**
  52271. * On long press
  52272. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52273. */
  52274. get: function () {
  52275. return ActionManager._OnLongPressTrigger;
  52276. },
  52277. enumerable: true,
  52278. configurable: true
  52279. });
  52280. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52281. /**
  52282. * On pointer over
  52283. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52284. */
  52285. get: function () {
  52286. return ActionManager._OnPointerOverTrigger;
  52287. },
  52288. enumerable: true,
  52289. configurable: true
  52290. });
  52291. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52292. /**
  52293. * On pointer out
  52294. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52295. */
  52296. get: function () {
  52297. return ActionManager._OnPointerOutTrigger;
  52298. },
  52299. enumerable: true,
  52300. configurable: true
  52301. });
  52302. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52303. /**
  52304. * On every frame
  52305. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52306. */
  52307. get: function () {
  52308. return ActionManager._OnEveryFrameTrigger;
  52309. },
  52310. enumerable: true,
  52311. configurable: true
  52312. });
  52313. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52314. /**
  52315. * On intersection enter
  52316. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52317. */
  52318. get: function () {
  52319. return ActionManager._OnIntersectionEnterTrigger;
  52320. },
  52321. enumerable: true,
  52322. configurable: true
  52323. });
  52324. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52325. /**
  52326. * On intersection exit
  52327. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52328. */
  52329. get: function () {
  52330. return ActionManager._OnIntersectionExitTrigger;
  52331. },
  52332. enumerable: true,
  52333. configurable: true
  52334. });
  52335. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52336. /**
  52337. * On key down
  52338. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52339. */
  52340. get: function () {
  52341. return ActionManager._OnKeyDownTrigger;
  52342. },
  52343. enumerable: true,
  52344. configurable: true
  52345. });
  52346. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52347. /**
  52348. * On key up
  52349. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52350. */
  52351. get: function () {
  52352. return ActionManager._OnKeyUpTrigger;
  52353. },
  52354. enumerable: true,
  52355. configurable: true
  52356. });
  52357. // Methods
  52358. /**
  52359. * Releases all associated resources
  52360. */
  52361. ActionManager.prototype.dispose = function () {
  52362. var index = this._scene.actionManagers.indexOf(this);
  52363. for (var i = 0; i < this.actions.length; i++) {
  52364. var action = this.actions[i];
  52365. ActionManager.Triggers[action.trigger]--;
  52366. if (ActionManager.Triggers[action.trigger] === 0) {
  52367. delete ActionManager.Triggers[action.trigger];
  52368. }
  52369. }
  52370. if (index > -1) {
  52371. this._scene.actionManagers.splice(index, 1);
  52372. }
  52373. };
  52374. /**
  52375. * Gets hosting scene
  52376. * @returns the hosting scene
  52377. */
  52378. ActionManager.prototype.getScene = function () {
  52379. return this._scene;
  52380. };
  52381. /**
  52382. * Does this action manager handles actions of any of the given triggers
  52383. * @param triggers defines the triggers to be tested
  52384. * @return a boolean indicating whether one (or more) of the triggers is handled
  52385. */
  52386. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52387. for (var index = 0; index < this.actions.length; index++) {
  52388. var action = this.actions[index];
  52389. if (triggers.indexOf(action.trigger) > -1) {
  52390. return true;
  52391. }
  52392. }
  52393. return false;
  52394. };
  52395. /**
  52396. * Does this action manager handles actions of a given trigger
  52397. * @param trigger defines the trigger to be tested
  52398. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52399. * @return whether the trigger is handled
  52400. */
  52401. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52402. for (var index = 0; index < this.actions.length; index++) {
  52403. var action = this.actions[index];
  52404. if (action.trigger === trigger) {
  52405. if (parameterPredicate) {
  52406. if (parameterPredicate(action.getTriggerParameter())) {
  52407. return true;
  52408. }
  52409. }
  52410. else {
  52411. return true;
  52412. }
  52413. }
  52414. }
  52415. return false;
  52416. };
  52417. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52418. /**
  52419. * Does this action manager has pointer triggers
  52420. */
  52421. get: function () {
  52422. for (var index = 0; index < this.actions.length; index++) {
  52423. var action = this.actions[index];
  52424. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52425. return true;
  52426. }
  52427. }
  52428. return false;
  52429. },
  52430. enumerable: true,
  52431. configurable: true
  52432. });
  52433. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52434. /**
  52435. * Does this action manager has pick triggers
  52436. */
  52437. get: function () {
  52438. for (var index = 0; index < this.actions.length; index++) {
  52439. var action = this.actions[index];
  52440. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52441. return true;
  52442. }
  52443. }
  52444. return false;
  52445. },
  52446. enumerable: true,
  52447. configurable: true
  52448. });
  52449. Object.defineProperty(ActionManager, "HasTriggers", {
  52450. /**
  52451. * Does exist one action manager with at least one trigger
  52452. **/
  52453. get: function () {
  52454. for (var t in ActionManager.Triggers) {
  52455. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52456. return true;
  52457. }
  52458. }
  52459. return false;
  52460. },
  52461. enumerable: true,
  52462. configurable: true
  52463. });
  52464. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52465. /**
  52466. * Does exist one action manager with at least one pick trigger
  52467. **/
  52468. get: function () {
  52469. for (var t in ActionManager.Triggers) {
  52470. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52471. var t_int = parseInt(t);
  52472. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52473. return true;
  52474. }
  52475. }
  52476. }
  52477. return false;
  52478. },
  52479. enumerable: true,
  52480. configurable: true
  52481. });
  52482. /**
  52483. * Does exist one action manager that handles actions of a given trigger
  52484. * @param trigger defines the trigger to be tested
  52485. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52486. **/
  52487. ActionManager.HasSpecificTrigger = function (trigger) {
  52488. for (var t in ActionManager.Triggers) {
  52489. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52490. var t_int = parseInt(t);
  52491. if (t_int === trigger) {
  52492. return true;
  52493. }
  52494. }
  52495. }
  52496. return false;
  52497. };
  52498. /**
  52499. * Registers an action to this action manager
  52500. * @param action defines the action to be registered
  52501. * @return the action amended (prepared) after registration
  52502. */
  52503. ActionManager.prototype.registerAction = function (action) {
  52504. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52505. if (this.getScene().actionManager !== this) {
  52506. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52507. return null;
  52508. }
  52509. }
  52510. this.actions.push(action);
  52511. if (ActionManager.Triggers[action.trigger]) {
  52512. ActionManager.Triggers[action.trigger]++;
  52513. }
  52514. else {
  52515. ActionManager.Triggers[action.trigger] = 1;
  52516. }
  52517. action._actionManager = this;
  52518. action._prepare();
  52519. return action;
  52520. };
  52521. /**
  52522. * Unregisters an action to this action manager
  52523. * @param action defines the action to be unregistered
  52524. * @return a boolean indicating whether the action has been unregistered
  52525. */
  52526. ActionManager.prototype.unregisterAction = function (action) {
  52527. var index = this.actions.indexOf(action);
  52528. if (index !== -1) {
  52529. this.actions.splice(index, 1);
  52530. ActionManager.Triggers[action.trigger] -= 1;
  52531. if (ActionManager.Triggers[action.trigger] === 0) {
  52532. delete ActionManager.Triggers[action.trigger];
  52533. }
  52534. delete action._actionManager;
  52535. return true;
  52536. }
  52537. return false;
  52538. };
  52539. /**
  52540. * Process a specific trigger
  52541. * @param trigger defines the trigger to process
  52542. * @param evt defines the event details to be processed
  52543. */
  52544. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52545. for (var index = 0; index < this.actions.length; index++) {
  52546. var action = this.actions[index];
  52547. if (action.trigger === trigger) {
  52548. if (evt) {
  52549. if (trigger === ActionManager.OnKeyUpTrigger
  52550. || trigger === ActionManager.OnKeyDownTrigger) {
  52551. var parameter = action.getTriggerParameter();
  52552. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52553. if (!parameter.toLowerCase) {
  52554. continue;
  52555. }
  52556. var lowerCase = parameter.toLowerCase();
  52557. if (lowerCase !== evt.sourceEvent.key) {
  52558. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52559. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52560. if (actualkey !== lowerCase) {
  52561. continue;
  52562. }
  52563. }
  52564. }
  52565. }
  52566. }
  52567. action._executeCurrent(evt);
  52568. }
  52569. }
  52570. };
  52571. /** @hidden */
  52572. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52573. var properties = propertyPath.split(".");
  52574. for (var index = 0; index < properties.length - 1; index++) {
  52575. target = target[properties[index]];
  52576. }
  52577. return target;
  52578. };
  52579. /** @hidden */
  52580. ActionManager.prototype._getProperty = function (propertyPath) {
  52581. var properties = propertyPath.split(".");
  52582. return properties[properties.length - 1];
  52583. };
  52584. /**
  52585. * Serialize this manager to a JSON object
  52586. * @param name defines the property name to store this manager
  52587. * @returns a JSON representation of this manager
  52588. */
  52589. ActionManager.prototype.serialize = function (name) {
  52590. var root = {
  52591. children: new Array(),
  52592. name: name,
  52593. type: 3,
  52594. properties: new Array() // Empty for root but required
  52595. };
  52596. for (var i = 0; i < this.actions.length; i++) {
  52597. var triggerObject = {
  52598. type: 0,
  52599. children: new Array(),
  52600. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52601. properties: new Array()
  52602. };
  52603. var triggerOptions = this.actions[i].triggerOptions;
  52604. if (triggerOptions && typeof triggerOptions !== "number") {
  52605. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52606. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52607. }
  52608. else {
  52609. var parameter = {};
  52610. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52611. if (triggerOptions.parameter.mesh) {
  52612. parameter._meshId = triggerOptions.parameter.mesh.id;
  52613. }
  52614. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52615. }
  52616. }
  52617. // Serialize child action, recursively
  52618. this.actions[i].serialize(triggerObject);
  52619. // Add serialized trigger
  52620. root.children.push(triggerObject);
  52621. }
  52622. return root;
  52623. };
  52624. /**
  52625. * Creates a new ActionManager from a JSON data
  52626. * @param parsedActions defines the JSON data to read from
  52627. * @param object defines the hosting mesh
  52628. * @param scene defines the hosting scene
  52629. */
  52630. ActionManager.Parse = function (parsedActions, object, scene) {
  52631. var actionManager = new ActionManager(scene);
  52632. if (object === null)
  52633. scene.actionManager = actionManager;
  52634. else
  52635. object.actionManager = actionManager;
  52636. // instanciate a new object
  52637. var instanciate = function (name, params) {
  52638. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52639. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52640. newInstance.constructor.apply(newInstance, params);
  52641. return newInstance;
  52642. };
  52643. var parseParameter = function (name, value, target, propertyPath) {
  52644. if (propertyPath === null) {
  52645. // String, boolean or float
  52646. var floatValue = parseFloat(value);
  52647. if (value === "true" || value === "false")
  52648. return value === "true";
  52649. else
  52650. return isNaN(floatValue) ? value : floatValue;
  52651. }
  52652. var effectiveTarget = propertyPath.split(".");
  52653. var values = value.split(",");
  52654. // Get effective Target
  52655. for (var i = 0; i < effectiveTarget.length; i++) {
  52656. target = target[effectiveTarget[i]];
  52657. }
  52658. // Return appropriate value with its type
  52659. if (typeof (target) === "boolean")
  52660. return values[0] === "true";
  52661. if (typeof (target) === "string")
  52662. return values[0];
  52663. // Parameters with multiple values such as Vector3 etc.
  52664. var split = new Array();
  52665. for (var i = 0; i < values.length; i++)
  52666. split.push(parseFloat(values[i]));
  52667. if (target instanceof BABYLON.Vector3)
  52668. return BABYLON.Vector3.FromArray(split);
  52669. if (target instanceof BABYLON.Vector4)
  52670. return BABYLON.Vector4.FromArray(split);
  52671. if (target instanceof BABYLON.Color3)
  52672. return BABYLON.Color3.FromArray(split);
  52673. if (target instanceof BABYLON.Color4)
  52674. return BABYLON.Color4.FromArray(split);
  52675. return parseFloat(values[0]);
  52676. };
  52677. // traverse graph per trigger
  52678. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52679. if (combineArray === void 0) { combineArray = null; }
  52680. if (parsedAction.detached)
  52681. return;
  52682. var parameters = new Array();
  52683. var target = null;
  52684. var propertyPath = null;
  52685. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52686. // Parameters
  52687. if (parsedAction.type === 2)
  52688. parameters.push(actionManager);
  52689. else
  52690. parameters.push(trigger);
  52691. if (combine) {
  52692. var actions = new Array();
  52693. for (var j = 0; j < parsedAction.combine.length; j++) {
  52694. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52695. }
  52696. parameters.push(actions);
  52697. }
  52698. else {
  52699. for (var i = 0; i < parsedAction.properties.length; i++) {
  52700. var value = parsedAction.properties[i].value;
  52701. var name = parsedAction.properties[i].name;
  52702. var targetType = parsedAction.properties[i].targetType;
  52703. if (name === "target")
  52704. if (targetType !== null && targetType === "SceneProperties")
  52705. value = target = scene;
  52706. else
  52707. value = target = scene.getNodeByName(value);
  52708. else if (name === "parent")
  52709. value = scene.getNodeByName(value);
  52710. else if (name === "sound")
  52711. value = scene.getSoundByName(value);
  52712. else if (name !== "propertyPath") {
  52713. if (parsedAction.type === 2 && name === "operator")
  52714. value = BABYLON.ValueCondition[value];
  52715. else
  52716. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52717. }
  52718. else {
  52719. propertyPath = value;
  52720. }
  52721. parameters.push(value);
  52722. }
  52723. }
  52724. if (combineArray === null) {
  52725. parameters.push(condition);
  52726. }
  52727. else {
  52728. parameters.push(null);
  52729. }
  52730. // If interpolate value action
  52731. if (parsedAction.name === "InterpolateValueAction") {
  52732. var param = parameters[parameters.length - 2];
  52733. parameters[parameters.length - 1] = param;
  52734. parameters[parameters.length - 2] = condition;
  52735. }
  52736. // Action or condition(s) and not CombineAction
  52737. var newAction = instanciate(parsedAction.name, parameters);
  52738. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52739. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52740. if (action)
  52741. action.then(nothing);
  52742. else
  52743. actionManager.registerAction(nothing);
  52744. action = nothing;
  52745. }
  52746. if (combineArray === null) {
  52747. if (newAction instanceof BABYLON.Condition) {
  52748. condition = newAction;
  52749. newAction = action;
  52750. }
  52751. else {
  52752. condition = null;
  52753. if (action)
  52754. action.then(newAction);
  52755. else
  52756. actionManager.registerAction(newAction);
  52757. }
  52758. }
  52759. else {
  52760. combineArray.push(newAction);
  52761. }
  52762. for (var i = 0; i < parsedAction.children.length; i++)
  52763. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52764. };
  52765. // triggers
  52766. for (var i = 0; i < parsedActions.children.length; i++) {
  52767. var triggerParams;
  52768. var trigger = parsedActions.children[i];
  52769. if (trigger.properties.length > 0) {
  52770. var param = trigger.properties[0].value;
  52771. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52772. if (value._meshId) {
  52773. value.mesh = scene.getMeshByID(value._meshId);
  52774. }
  52775. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52776. }
  52777. else
  52778. triggerParams = ActionManager[trigger.name];
  52779. for (var j = 0; j < trigger.children.length; j++) {
  52780. if (!trigger.detached)
  52781. traverse(trigger.children[j], triggerParams, null, null);
  52782. }
  52783. }
  52784. };
  52785. /**
  52786. * Get a trigger name by index
  52787. * @param trigger defines the trigger index
  52788. * @returns a trigger name
  52789. */
  52790. ActionManager.GetTriggerName = function (trigger) {
  52791. switch (trigger) {
  52792. case 0: return "NothingTrigger";
  52793. case 1: return "OnPickTrigger";
  52794. case 2: return "OnLeftPickTrigger";
  52795. case 3: return "OnRightPickTrigger";
  52796. case 4: return "OnCenterPickTrigger";
  52797. case 5: return "OnPickDownTrigger";
  52798. case 6: return "OnPickUpTrigger";
  52799. case 7: return "OnLongPressTrigger";
  52800. case 8: return "OnPointerOverTrigger";
  52801. case 9: return "OnPointerOutTrigger";
  52802. case 10: return "OnEveryFrameTrigger";
  52803. case 11: return "OnIntersectionEnterTrigger";
  52804. case 12: return "OnIntersectionExitTrigger";
  52805. case 13: return "OnKeyDownTrigger";
  52806. case 14: return "OnKeyUpTrigger";
  52807. case 15: return "OnPickOutTrigger";
  52808. default: return "";
  52809. }
  52810. };
  52811. // Statics
  52812. ActionManager._NothingTrigger = 0;
  52813. ActionManager._OnPickTrigger = 1;
  52814. ActionManager._OnLeftPickTrigger = 2;
  52815. ActionManager._OnRightPickTrigger = 3;
  52816. ActionManager._OnCenterPickTrigger = 4;
  52817. ActionManager._OnPickDownTrigger = 5;
  52818. ActionManager._OnDoublePickTrigger = 6;
  52819. ActionManager._OnPickUpTrigger = 7;
  52820. ActionManager._OnLongPressTrigger = 8;
  52821. ActionManager._OnPointerOverTrigger = 9;
  52822. ActionManager._OnPointerOutTrigger = 10;
  52823. ActionManager._OnEveryFrameTrigger = 11;
  52824. ActionManager._OnIntersectionEnterTrigger = 12;
  52825. ActionManager._OnIntersectionExitTrigger = 13;
  52826. ActionManager._OnKeyDownTrigger = 14;
  52827. ActionManager._OnKeyUpTrigger = 15;
  52828. ActionManager._OnPickOutTrigger = 16;
  52829. /** Gets the list of active triggers */
  52830. ActionManager.Triggers = {};
  52831. return ActionManager;
  52832. }());
  52833. BABYLON.ActionManager = ActionManager;
  52834. })(BABYLON || (BABYLON = {}));
  52835. //# sourceMappingURL=babylon.actionManager.js.map
  52836. var BABYLON;
  52837. (function (BABYLON) {
  52838. var InterpolateValueAction = /** @class */ (function (_super) {
  52839. __extends(InterpolateValueAction, _super);
  52840. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52841. if (duration === void 0) { duration = 1000; }
  52842. var _this = _super.call(this, triggerOptions, condition) || this;
  52843. _this.propertyPath = propertyPath;
  52844. _this.value = value;
  52845. _this.duration = duration;
  52846. _this.stopOtherAnimations = stopOtherAnimations;
  52847. _this.onInterpolationDone = onInterpolationDone;
  52848. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52849. _this._target = _this._effectiveTarget = target;
  52850. return _this;
  52851. }
  52852. InterpolateValueAction.prototype._prepare = function () {
  52853. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52854. this._property = this._getProperty(this.propertyPath);
  52855. };
  52856. InterpolateValueAction.prototype.execute = function () {
  52857. var _this = this;
  52858. var scene = this._actionManager.getScene();
  52859. var keys = [
  52860. {
  52861. frame: 0,
  52862. value: this._effectiveTarget[this._property]
  52863. }, {
  52864. frame: 100,
  52865. value: this.value
  52866. }
  52867. ];
  52868. var dataType;
  52869. if (typeof this.value === "number") {
  52870. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52871. }
  52872. else if (this.value instanceof BABYLON.Color3) {
  52873. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52874. }
  52875. else if (this.value instanceof BABYLON.Vector3) {
  52876. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52877. }
  52878. else if (this.value instanceof BABYLON.Matrix) {
  52879. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52880. }
  52881. else if (this.value instanceof BABYLON.Quaternion) {
  52882. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  52883. }
  52884. else {
  52885. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  52886. return;
  52887. }
  52888. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  52889. animation.setKeys(keys);
  52890. if (this.stopOtherAnimations) {
  52891. scene.stopAnimation(this._effectiveTarget);
  52892. }
  52893. var wrapper = function () {
  52894. _this.onInterpolationDoneObservable.notifyObservers(_this);
  52895. if (_this.onInterpolationDone) {
  52896. _this.onInterpolationDone();
  52897. }
  52898. };
  52899. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  52900. };
  52901. InterpolateValueAction.prototype.serialize = function (parent) {
  52902. return _super.prototype._serialize.call(this, {
  52903. name: "InterpolateValueAction",
  52904. properties: [
  52905. BABYLON.Action._GetTargetProperty(this._target),
  52906. { name: "propertyPath", value: this.propertyPath },
  52907. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52908. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  52909. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  52910. ]
  52911. }, parent);
  52912. };
  52913. return InterpolateValueAction;
  52914. }(BABYLON.Action));
  52915. BABYLON.InterpolateValueAction = InterpolateValueAction;
  52916. })(BABYLON || (BABYLON = {}));
  52917. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  52918. var BABYLON;
  52919. (function (BABYLON) {
  52920. var SwitchBooleanAction = /** @class */ (function (_super) {
  52921. __extends(SwitchBooleanAction, _super);
  52922. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  52923. var _this = _super.call(this, triggerOptions, condition) || this;
  52924. _this.propertyPath = propertyPath;
  52925. _this._target = _this._effectiveTarget = target;
  52926. return _this;
  52927. }
  52928. SwitchBooleanAction.prototype._prepare = function () {
  52929. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52930. this._property = this._getProperty(this.propertyPath);
  52931. };
  52932. SwitchBooleanAction.prototype.execute = function () {
  52933. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  52934. };
  52935. SwitchBooleanAction.prototype.serialize = function (parent) {
  52936. return _super.prototype._serialize.call(this, {
  52937. name: "SwitchBooleanAction",
  52938. properties: [
  52939. BABYLON.Action._GetTargetProperty(this._target),
  52940. { name: "propertyPath", value: this.propertyPath }
  52941. ]
  52942. }, parent);
  52943. };
  52944. return SwitchBooleanAction;
  52945. }(BABYLON.Action));
  52946. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  52947. var SetStateAction = /** @class */ (function (_super) {
  52948. __extends(SetStateAction, _super);
  52949. function SetStateAction(triggerOptions, target, value, condition) {
  52950. var _this = _super.call(this, triggerOptions, condition) || this;
  52951. _this.value = value;
  52952. _this._target = target;
  52953. return _this;
  52954. }
  52955. SetStateAction.prototype.execute = function () {
  52956. this._target.state = this.value;
  52957. };
  52958. SetStateAction.prototype.serialize = function (parent) {
  52959. return _super.prototype._serialize.call(this, {
  52960. name: "SetStateAction",
  52961. properties: [
  52962. BABYLON.Action._GetTargetProperty(this._target),
  52963. { name: "value", value: this.value }
  52964. ]
  52965. }, parent);
  52966. };
  52967. return SetStateAction;
  52968. }(BABYLON.Action));
  52969. BABYLON.SetStateAction = SetStateAction;
  52970. var SetValueAction = /** @class */ (function (_super) {
  52971. __extends(SetValueAction, _super);
  52972. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  52973. var _this = _super.call(this, triggerOptions, condition) || this;
  52974. _this.propertyPath = propertyPath;
  52975. _this.value = value;
  52976. _this._target = _this._effectiveTarget = target;
  52977. return _this;
  52978. }
  52979. SetValueAction.prototype._prepare = function () {
  52980. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52981. this._property = this._getProperty(this.propertyPath);
  52982. };
  52983. SetValueAction.prototype.execute = function () {
  52984. this._effectiveTarget[this._property] = this.value;
  52985. if (this._target.markAsDirty) {
  52986. this._target.markAsDirty(this._property);
  52987. }
  52988. };
  52989. SetValueAction.prototype.serialize = function (parent) {
  52990. return _super.prototype._serialize.call(this, {
  52991. name: "SetValueAction",
  52992. properties: [
  52993. BABYLON.Action._GetTargetProperty(this._target),
  52994. { name: "propertyPath", value: this.propertyPath },
  52995. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52996. ]
  52997. }, parent);
  52998. };
  52999. return SetValueAction;
  53000. }(BABYLON.Action));
  53001. BABYLON.SetValueAction = SetValueAction;
  53002. var IncrementValueAction = /** @class */ (function (_super) {
  53003. __extends(IncrementValueAction, _super);
  53004. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53005. var _this = _super.call(this, triggerOptions, condition) || this;
  53006. _this.propertyPath = propertyPath;
  53007. _this.value = value;
  53008. _this._target = _this._effectiveTarget = target;
  53009. return _this;
  53010. }
  53011. IncrementValueAction.prototype._prepare = function () {
  53012. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53013. this._property = this._getProperty(this.propertyPath);
  53014. if (typeof this._effectiveTarget[this._property] !== "number") {
  53015. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53016. }
  53017. };
  53018. IncrementValueAction.prototype.execute = function () {
  53019. this._effectiveTarget[this._property] += this.value;
  53020. if (this._target.markAsDirty) {
  53021. this._target.markAsDirty(this._property);
  53022. }
  53023. };
  53024. IncrementValueAction.prototype.serialize = function (parent) {
  53025. return _super.prototype._serialize.call(this, {
  53026. name: "IncrementValueAction",
  53027. properties: [
  53028. BABYLON.Action._GetTargetProperty(this._target),
  53029. { name: "propertyPath", value: this.propertyPath },
  53030. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53031. ]
  53032. }, parent);
  53033. };
  53034. return IncrementValueAction;
  53035. }(BABYLON.Action));
  53036. BABYLON.IncrementValueAction = IncrementValueAction;
  53037. var PlayAnimationAction = /** @class */ (function (_super) {
  53038. __extends(PlayAnimationAction, _super);
  53039. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53040. var _this = _super.call(this, triggerOptions, condition) || this;
  53041. _this.from = from;
  53042. _this.to = to;
  53043. _this.loop = loop;
  53044. _this._target = target;
  53045. return _this;
  53046. }
  53047. PlayAnimationAction.prototype._prepare = function () {
  53048. };
  53049. PlayAnimationAction.prototype.execute = function () {
  53050. var scene = this._actionManager.getScene();
  53051. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53052. };
  53053. PlayAnimationAction.prototype.serialize = function (parent) {
  53054. return _super.prototype._serialize.call(this, {
  53055. name: "PlayAnimationAction",
  53056. properties: [
  53057. BABYLON.Action._GetTargetProperty(this._target),
  53058. { name: "from", value: String(this.from) },
  53059. { name: "to", value: String(this.to) },
  53060. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53061. ]
  53062. }, parent);
  53063. };
  53064. return PlayAnimationAction;
  53065. }(BABYLON.Action));
  53066. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53067. var StopAnimationAction = /** @class */ (function (_super) {
  53068. __extends(StopAnimationAction, _super);
  53069. function StopAnimationAction(triggerOptions, target, condition) {
  53070. var _this = _super.call(this, triggerOptions, condition) || this;
  53071. _this._target = target;
  53072. return _this;
  53073. }
  53074. StopAnimationAction.prototype._prepare = function () {
  53075. };
  53076. StopAnimationAction.prototype.execute = function () {
  53077. var scene = this._actionManager.getScene();
  53078. scene.stopAnimation(this._target);
  53079. };
  53080. StopAnimationAction.prototype.serialize = function (parent) {
  53081. return _super.prototype._serialize.call(this, {
  53082. name: "StopAnimationAction",
  53083. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53084. }, parent);
  53085. };
  53086. return StopAnimationAction;
  53087. }(BABYLON.Action));
  53088. BABYLON.StopAnimationAction = StopAnimationAction;
  53089. var DoNothingAction = /** @class */ (function (_super) {
  53090. __extends(DoNothingAction, _super);
  53091. function DoNothingAction(triggerOptions, condition) {
  53092. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53093. return _super.call(this, triggerOptions, condition) || this;
  53094. }
  53095. DoNothingAction.prototype.execute = function () {
  53096. };
  53097. DoNothingAction.prototype.serialize = function (parent) {
  53098. return _super.prototype._serialize.call(this, {
  53099. name: "DoNothingAction",
  53100. properties: []
  53101. }, parent);
  53102. };
  53103. return DoNothingAction;
  53104. }(BABYLON.Action));
  53105. BABYLON.DoNothingAction = DoNothingAction;
  53106. var CombineAction = /** @class */ (function (_super) {
  53107. __extends(CombineAction, _super);
  53108. function CombineAction(triggerOptions, children, condition) {
  53109. var _this = _super.call(this, triggerOptions, condition) || this;
  53110. _this.children = children;
  53111. return _this;
  53112. }
  53113. CombineAction.prototype._prepare = function () {
  53114. for (var index = 0; index < this.children.length; index++) {
  53115. this.children[index]._actionManager = this._actionManager;
  53116. this.children[index]._prepare();
  53117. }
  53118. };
  53119. CombineAction.prototype.execute = function (evt) {
  53120. for (var index = 0; index < this.children.length; index++) {
  53121. this.children[index].execute(evt);
  53122. }
  53123. };
  53124. CombineAction.prototype.serialize = function (parent) {
  53125. var serializationObject = _super.prototype._serialize.call(this, {
  53126. name: "CombineAction",
  53127. properties: [],
  53128. combine: []
  53129. }, parent);
  53130. for (var i = 0; i < this.children.length; i++) {
  53131. serializationObject.combine.push(this.children[i].serialize(null));
  53132. }
  53133. return serializationObject;
  53134. };
  53135. return CombineAction;
  53136. }(BABYLON.Action));
  53137. BABYLON.CombineAction = CombineAction;
  53138. var ExecuteCodeAction = /** @class */ (function (_super) {
  53139. __extends(ExecuteCodeAction, _super);
  53140. function ExecuteCodeAction(triggerOptions, func, condition) {
  53141. var _this = _super.call(this, triggerOptions, condition) || this;
  53142. _this.func = func;
  53143. return _this;
  53144. }
  53145. ExecuteCodeAction.prototype.execute = function (evt) {
  53146. this.func(evt);
  53147. };
  53148. return ExecuteCodeAction;
  53149. }(BABYLON.Action));
  53150. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53151. var SetParentAction = /** @class */ (function (_super) {
  53152. __extends(SetParentAction, _super);
  53153. function SetParentAction(triggerOptions, target, parent, condition) {
  53154. var _this = _super.call(this, triggerOptions, condition) || this;
  53155. _this._target = target;
  53156. _this._parent = parent;
  53157. return _this;
  53158. }
  53159. SetParentAction.prototype._prepare = function () {
  53160. };
  53161. SetParentAction.prototype.execute = function () {
  53162. if (this._target.parent === this._parent) {
  53163. return;
  53164. }
  53165. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53166. invertParentWorldMatrix.invert();
  53167. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53168. this._target.parent = this._parent;
  53169. };
  53170. SetParentAction.prototype.serialize = function (parent) {
  53171. return _super.prototype._serialize.call(this, {
  53172. name: "SetParentAction",
  53173. properties: [
  53174. BABYLON.Action._GetTargetProperty(this._target),
  53175. BABYLON.Action._GetTargetProperty(this._parent),
  53176. ]
  53177. }, parent);
  53178. };
  53179. return SetParentAction;
  53180. }(BABYLON.Action));
  53181. BABYLON.SetParentAction = SetParentAction;
  53182. var PlaySoundAction = /** @class */ (function (_super) {
  53183. __extends(PlaySoundAction, _super);
  53184. function PlaySoundAction(triggerOptions, sound, condition) {
  53185. var _this = _super.call(this, triggerOptions, condition) || this;
  53186. _this._sound = sound;
  53187. return _this;
  53188. }
  53189. PlaySoundAction.prototype._prepare = function () {
  53190. };
  53191. PlaySoundAction.prototype.execute = function () {
  53192. if (this._sound !== undefined)
  53193. this._sound.play();
  53194. };
  53195. PlaySoundAction.prototype.serialize = function (parent) {
  53196. return _super.prototype._serialize.call(this, {
  53197. name: "PlaySoundAction",
  53198. properties: [{ name: "sound", value: this._sound.name }]
  53199. }, parent);
  53200. };
  53201. return PlaySoundAction;
  53202. }(BABYLON.Action));
  53203. BABYLON.PlaySoundAction = PlaySoundAction;
  53204. var StopSoundAction = /** @class */ (function (_super) {
  53205. __extends(StopSoundAction, _super);
  53206. function StopSoundAction(triggerOptions, sound, condition) {
  53207. var _this = _super.call(this, triggerOptions, condition) || this;
  53208. _this._sound = sound;
  53209. return _this;
  53210. }
  53211. StopSoundAction.prototype._prepare = function () {
  53212. };
  53213. StopSoundAction.prototype.execute = function () {
  53214. if (this._sound !== undefined)
  53215. this._sound.stop();
  53216. };
  53217. StopSoundAction.prototype.serialize = function (parent) {
  53218. return _super.prototype._serialize.call(this, {
  53219. name: "StopSoundAction",
  53220. properties: [{ name: "sound", value: this._sound.name }]
  53221. }, parent);
  53222. };
  53223. return StopSoundAction;
  53224. }(BABYLON.Action));
  53225. BABYLON.StopSoundAction = StopSoundAction;
  53226. })(BABYLON || (BABYLON = {}));
  53227. //# sourceMappingURL=babylon.directActions.js.map
  53228. var BABYLON;
  53229. (function (BABYLON) {
  53230. var SpriteManager = /** @class */ (function () {
  53231. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53232. if (epsilon === void 0) { epsilon = 0.01; }
  53233. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53234. this.name = name;
  53235. this.sprites = new Array();
  53236. this.renderingGroupId = 0;
  53237. this.layerMask = 0x0FFFFFFF;
  53238. this.fogEnabled = true;
  53239. this.isPickable = false;
  53240. /**
  53241. * An event triggered when the manager is disposed.
  53242. */
  53243. this.onDisposeObservable = new BABYLON.Observable();
  53244. this._vertexBuffers = {};
  53245. this._capacity = capacity;
  53246. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53247. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53248. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53249. if (cellSize.width && cellSize.height) {
  53250. this.cellWidth = cellSize.width;
  53251. this.cellHeight = cellSize.height;
  53252. }
  53253. else if (cellSize !== undefined) {
  53254. this.cellWidth = cellSize;
  53255. this.cellHeight = cellSize;
  53256. }
  53257. else {
  53258. return;
  53259. }
  53260. this._epsilon = epsilon;
  53261. this._scene = scene;
  53262. this._scene.spriteManagers.push(this);
  53263. var indices = [];
  53264. var index = 0;
  53265. for (var count = 0; count < capacity; count++) {
  53266. indices.push(index);
  53267. indices.push(index + 1);
  53268. indices.push(index + 2);
  53269. indices.push(index);
  53270. indices.push(index + 2);
  53271. indices.push(index + 3);
  53272. index += 4;
  53273. }
  53274. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53275. // VBO
  53276. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53277. this._vertexData = new Float32Array(capacity * 16 * 4);
  53278. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53279. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53280. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53281. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53282. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53283. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53284. this._vertexBuffers["options"] = options;
  53285. this._vertexBuffers["cellInfo"] = cellInfo;
  53286. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53287. // Effects
  53288. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53289. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53290. }
  53291. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53292. set: function (callback) {
  53293. if (this._onDisposeObserver) {
  53294. this.onDisposeObservable.remove(this._onDisposeObserver);
  53295. }
  53296. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53297. },
  53298. enumerable: true,
  53299. configurable: true
  53300. });
  53301. Object.defineProperty(SpriteManager.prototype, "texture", {
  53302. get: function () {
  53303. return this._spriteTexture;
  53304. },
  53305. set: function (value) {
  53306. this._spriteTexture = value;
  53307. },
  53308. enumerable: true,
  53309. configurable: true
  53310. });
  53311. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53312. var arrayOffset = index * 16;
  53313. if (offsetX === 0)
  53314. offsetX = this._epsilon;
  53315. else if (offsetX === 1)
  53316. offsetX = 1 - this._epsilon;
  53317. if (offsetY === 0)
  53318. offsetY = this._epsilon;
  53319. else if (offsetY === 1)
  53320. offsetY = 1 - this._epsilon;
  53321. this._vertexData[arrayOffset] = sprite.position.x;
  53322. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53323. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53324. this._vertexData[arrayOffset + 3] = sprite.angle;
  53325. this._vertexData[arrayOffset + 4] = sprite.width;
  53326. this._vertexData[arrayOffset + 5] = sprite.height;
  53327. this._vertexData[arrayOffset + 6] = offsetX;
  53328. this._vertexData[arrayOffset + 7] = offsetY;
  53329. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53330. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53331. var offset = (sprite.cellIndex / rowSize) >> 0;
  53332. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53333. this._vertexData[arrayOffset + 11] = offset;
  53334. // Color
  53335. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53336. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53337. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53338. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53339. };
  53340. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53341. var count = Math.min(this._capacity, this.sprites.length);
  53342. var min = BABYLON.Vector3.Zero();
  53343. var max = BABYLON.Vector3.Zero();
  53344. var distance = Number.MAX_VALUE;
  53345. var currentSprite = null;
  53346. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53347. var cameraView = camera.getViewMatrix();
  53348. for (var index = 0; index < count; index++) {
  53349. var sprite = this.sprites[index];
  53350. if (!sprite) {
  53351. continue;
  53352. }
  53353. if (predicate) {
  53354. if (!predicate(sprite)) {
  53355. continue;
  53356. }
  53357. }
  53358. else if (!sprite.isPickable) {
  53359. continue;
  53360. }
  53361. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53362. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53363. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53364. if (ray.intersectsBoxMinMax(min, max)) {
  53365. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53366. if (distance > currentDistance) {
  53367. distance = currentDistance;
  53368. currentSprite = sprite;
  53369. if (fastCheck) {
  53370. break;
  53371. }
  53372. }
  53373. }
  53374. }
  53375. if (currentSprite) {
  53376. var result = new BABYLON.PickingInfo();
  53377. result.hit = true;
  53378. result.pickedSprite = currentSprite;
  53379. result.distance = distance;
  53380. return result;
  53381. }
  53382. return null;
  53383. };
  53384. SpriteManager.prototype.render = function () {
  53385. // Check
  53386. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53387. return;
  53388. var engine = this._scene.getEngine();
  53389. var baseSize = this._spriteTexture.getBaseSize();
  53390. // Sprites
  53391. var deltaTime = engine.getDeltaTime();
  53392. var max = Math.min(this._capacity, this.sprites.length);
  53393. var rowSize = baseSize.width / this.cellWidth;
  53394. var offset = 0;
  53395. for (var index = 0; index < max; index++) {
  53396. var sprite = this.sprites[index];
  53397. if (!sprite || !sprite.isVisible) {
  53398. continue;
  53399. }
  53400. sprite._animate(deltaTime);
  53401. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53402. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53403. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53404. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53405. }
  53406. this._buffer.update(this._vertexData);
  53407. // Render
  53408. var effect = this._effectBase;
  53409. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53410. effect = this._effectFog;
  53411. }
  53412. engine.enableEffect(effect);
  53413. var viewMatrix = this._scene.getViewMatrix();
  53414. effect.setTexture("diffuseSampler", this._spriteTexture);
  53415. effect.setMatrix("view", viewMatrix);
  53416. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53417. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53418. // Fog
  53419. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53420. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53421. effect.setColor3("vFogColor", this._scene.fogColor);
  53422. }
  53423. // VBOs
  53424. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53425. // Draw order
  53426. engine.setDepthFunctionToLessOrEqual();
  53427. effect.setBool("alphaTest", true);
  53428. engine.setColorWrite(false);
  53429. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53430. engine.setColorWrite(true);
  53431. effect.setBool("alphaTest", false);
  53432. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53433. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53434. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53435. };
  53436. SpriteManager.prototype.dispose = function () {
  53437. if (this._buffer) {
  53438. this._buffer.dispose();
  53439. this._buffer = null;
  53440. }
  53441. if (this._indexBuffer) {
  53442. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53443. this._indexBuffer = null;
  53444. }
  53445. if (this._spriteTexture) {
  53446. this._spriteTexture.dispose();
  53447. this._spriteTexture = null;
  53448. }
  53449. // Remove from scene
  53450. var index = this._scene.spriteManagers.indexOf(this);
  53451. this._scene.spriteManagers.splice(index, 1);
  53452. // Callback
  53453. this.onDisposeObservable.notifyObservers(this);
  53454. this.onDisposeObservable.clear();
  53455. };
  53456. return SpriteManager;
  53457. }());
  53458. BABYLON.SpriteManager = SpriteManager;
  53459. })(BABYLON || (BABYLON = {}));
  53460. //# sourceMappingURL=babylon.spriteManager.js.map
  53461. var BABYLON;
  53462. (function (BABYLON) {
  53463. var Sprite = /** @class */ (function () {
  53464. function Sprite(name, manager) {
  53465. this.name = name;
  53466. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53467. this.width = 1.0;
  53468. this.height = 1.0;
  53469. this.angle = 0;
  53470. this.cellIndex = 0;
  53471. this.invertU = 0;
  53472. this.invertV = 0;
  53473. this.animations = new Array();
  53474. this.isPickable = false;
  53475. this._animationStarted = false;
  53476. this._loopAnimation = false;
  53477. this._fromIndex = 0;
  53478. this._toIndex = 0;
  53479. this._delay = 0;
  53480. this._direction = 1;
  53481. this._time = 0;
  53482. /**
  53483. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53484. */
  53485. this.isVisible = true;
  53486. this._manager = manager;
  53487. this._manager.sprites.push(this);
  53488. this.position = BABYLON.Vector3.Zero();
  53489. }
  53490. Object.defineProperty(Sprite.prototype, "size", {
  53491. get: function () {
  53492. return this.width;
  53493. },
  53494. set: function (value) {
  53495. this.width = value;
  53496. this.height = value;
  53497. },
  53498. enumerable: true,
  53499. configurable: true
  53500. });
  53501. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53502. this._fromIndex = from;
  53503. this._toIndex = to;
  53504. this._loopAnimation = loop;
  53505. this._delay = delay;
  53506. this._animationStarted = true;
  53507. this._direction = from < to ? 1 : -1;
  53508. this.cellIndex = from;
  53509. this._time = 0;
  53510. this._onAnimationEnd = onAnimationEnd;
  53511. };
  53512. Sprite.prototype.stopAnimation = function () {
  53513. this._animationStarted = false;
  53514. };
  53515. Sprite.prototype._animate = function (deltaTime) {
  53516. if (!this._animationStarted)
  53517. return;
  53518. this._time += deltaTime;
  53519. if (this._time > this._delay) {
  53520. this._time = this._time % this._delay;
  53521. this.cellIndex += this._direction;
  53522. if (this.cellIndex > this._toIndex) {
  53523. if (this._loopAnimation) {
  53524. this.cellIndex = this._fromIndex;
  53525. }
  53526. else {
  53527. this.cellIndex = this._toIndex;
  53528. this._animationStarted = false;
  53529. if (this._onAnimationEnd) {
  53530. this._onAnimationEnd();
  53531. }
  53532. if (this.disposeWhenFinishedAnimating) {
  53533. this.dispose();
  53534. }
  53535. }
  53536. }
  53537. }
  53538. };
  53539. Sprite.prototype.dispose = function () {
  53540. for (var i = 0; i < this._manager.sprites.length; i++) {
  53541. if (this._manager.sprites[i] == this) {
  53542. this._manager.sprites.splice(i, 1);
  53543. }
  53544. }
  53545. };
  53546. return Sprite;
  53547. }());
  53548. BABYLON.Sprite = Sprite;
  53549. })(BABYLON || (BABYLON = {}));
  53550. //# sourceMappingURL=babylon.sprite.js.map
  53551. var BABYLON;
  53552. (function (BABYLON) {
  53553. var IntersectionInfo = /** @class */ (function () {
  53554. function IntersectionInfo(bu, bv, distance) {
  53555. this.bu = bu;
  53556. this.bv = bv;
  53557. this.distance = distance;
  53558. this.faceId = 0;
  53559. this.subMeshId = 0;
  53560. }
  53561. return IntersectionInfo;
  53562. }());
  53563. BABYLON.IntersectionInfo = IntersectionInfo;
  53564. /**
  53565. * Information about the result of picking within a scene
  53566. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53567. */
  53568. var PickingInfo = /** @class */ (function () {
  53569. function PickingInfo() {
  53570. /**
  53571. * If the pick collided with an object
  53572. */
  53573. this.hit = false;
  53574. /**
  53575. * Distance away where the pick collided
  53576. */
  53577. this.distance = 0;
  53578. /**
  53579. * The location of pick collision
  53580. */
  53581. this.pickedPoint = null;
  53582. /**
  53583. * The mesh corrisponding the the pick collision
  53584. */
  53585. this.pickedMesh = null;
  53586. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53587. this.bu = 0;
  53588. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53589. this.bv = 0;
  53590. /** The id of the face on the mesh that was picked */
  53591. this.faceId = -1;
  53592. /** Id of the the submesh that was picked */
  53593. this.subMeshId = 0;
  53594. /** If a sprite was picked, this will be the sprite the pick collided with */
  53595. this.pickedSprite = null;
  53596. /**
  53597. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53598. */
  53599. this.originMesh = null;
  53600. /**
  53601. * The ray that was used to perform the picking.
  53602. */
  53603. this.ray = null;
  53604. }
  53605. /**
  53606. * Gets the normal corrispodning to the face the pick collided with
  53607. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53608. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53609. * @returns The normal corrispodning to the face the pick collided with
  53610. */
  53611. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53612. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53613. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53614. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53615. return null;
  53616. }
  53617. var indices = this.pickedMesh.getIndices();
  53618. if (!indices) {
  53619. return null;
  53620. }
  53621. var result;
  53622. if (useVerticesNormals) {
  53623. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53624. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53625. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53626. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53627. normal0 = normal0.scale(this.bu);
  53628. normal1 = normal1.scale(this.bv);
  53629. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53630. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53631. }
  53632. else {
  53633. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53634. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53635. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53636. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53637. var p1p2 = vertex1.subtract(vertex2);
  53638. var p3p2 = vertex3.subtract(vertex2);
  53639. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53640. }
  53641. if (useWorldCoordinates) {
  53642. var wm = this.pickedMesh.getWorldMatrix();
  53643. if (this.pickedMesh.nonUniformScaling) {
  53644. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53645. wm = BABYLON.Tmp.Matrix[0];
  53646. wm.setTranslationFromFloats(0, 0, 0);
  53647. wm.invert();
  53648. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53649. wm = BABYLON.Tmp.Matrix[1];
  53650. }
  53651. result = BABYLON.Vector3.TransformNormal(result, wm);
  53652. }
  53653. result.normalize();
  53654. return result;
  53655. };
  53656. /**
  53657. * Gets the texture coordinates of where the pick occured
  53658. * @returns the vector containing the coordnates of the texture
  53659. */
  53660. PickingInfo.prototype.getTextureCoordinates = function () {
  53661. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53662. return null;
  53663. }
  53664. var indices = this.pickedMesh.getIndices();
  53665. if (!indices) {
  53666. return null;
  53667. }
  53668. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53669. if (!uvs) {
  53670. return null;
  53671. }
  53672. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53673. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53674. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53675. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53676. uv1 = uv1.scale(this.bu);
  53677. uv2 = uv2.scale(this.bv);
  53678. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53679. };
  53680. return PickingInfo;
  53681. }());
  53682. BABYLON.PickingInfo = PickingInfo;
  53683. })(BABYLON || (BABYLON = {}));
  53684. //# sourceMappingURL=babylon.pickingInfo.js.map
  53685. var BABYLON;
  53686. (function (BABYLON) {
  53687. var Ray = /** @class */ (function () {
  53688. function Ray(origin, direction, length) {
  53689. if (length === void 0) { length = Number.MAX_VALUE; }
  53690. this.origin = origin;
  53691. this.direction = direction;
  53692. this.length = length;
  53693. }
  53694. // Methods
  53695. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53696. var d = 0.0;
  53697. var maxValue = Number.MAX_VALUE;
  53698. var inv;
  53699. var min;
  53700. var max;
  53701. var temp;
  53702. if (Math.abs(this.direction.x) < 0.0000001) {
  53703. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53704. return false;
  53705. }
  53706. }
  53707. else {
  53708. inv = 1.0 / this.direction.x;
  53709. min = (minimum.x - this.origin.x) * inv;
  53710. max = (maximum.x - this.origin.x) * inv;
  53711. if (max === -Infinity) {
  53712. max = Infinity;
  53713. }
  53714. if (min > max) {
  53715. temp = min;
  53716. min = max;
  53717. max = temp;
  53718. }
  53719. d = Math.max(min, d);
  53720. maxValue = Math.min(max, maxValue);
  53721. if (d > maxValue) {
  53722. return false;
  53723. }
  53724. }
  53725. if (Math.abs(this.direction.y) < 0.0000001) {
  53726. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53727. return false;
  53728. }
  53729. }
  53730. else {
  53731. inv = 1.0 / this.direction.y;
  53732. min = (minimum.y - this.origin.y) * inv;
  53733. max = (maximum.y - this.origin.y) * inv;
  53734. if (max === -Infinity) {
  53735. max = Infinity;
  53736. }
  53737. if (min > max) {
  53738. temp = min;
  53739. min = max;
  53740. max = temp;
  53741. }
  53742. d = Math.max(min, d);
  53743. maxValue = Math.min(max, maxValue);
  53744. if (d > maxValue) {
  53745. return false;
  53746. }
  53747. }
  53748. if (Math.abs(this.direction.z) < 0.0000001) {
  53749. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53750. return false;
  53751. }
  53752. }
  53753. else {
  53754. inv = 1.0 / this.direction.z;
  53755. min = (minimum.z - this.origin.z) * inv;
  53756. max = (maximum.z - this.origin.z) * inv;
  53757. if (max === -Infinity) {
  53758. max = Infinity;
  53759. }
  53760. if (min > max) {
  53761. temp = min;
  53762. min = max;
  53763. max = temp;
  53764. }
  53765. d = Math.max(min, d);
  53766. maxValue = Math.min(max, maxValue);
  53767. if (d > maxValue) {
  53768. return false;
  53769. }
  53770. }
  53771. return true;
  53772. };
  53773. Ray.prototype.intersectsBox = function (box) {
  53774. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53775. };
  53776. Ray.prototype.intersectsSphere = function (sphere) {
  53777. var x = sphere.center.x - this.origin.x;
  53778. var y = sphere.center.y - this.origin.y;
  53779. var z = sphere.center.z - this.origin.z;
  53780. var pyth = (x * x) + (y * y) + (z * z);
  53781. var rr = sphere.radius * sphere.radius;
  53782. if (pyth <= rr) {
  53783. return true;
  53784. }
  53785. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53786. if (dot < 0.0) {
  53787. return false;
  53788. }
  53789. var temp = pyth - (dot * dot);
  53790. return temp <= rr;
  53791. };
  53792. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53793. if (!this._edge1) {
  53794. this._edge1 = BABYLON.Vector3.Zero();
  53795. this._edge2 = BABYLON.Vector3.Zero();
  53796. this._pvec = BABYLON.Vector3.Zero();
  53797. this._tvec = BABYLON.Vector3.Zero();
  53798. this._qvec = BABYLON.Vector3.Zero();
  53799. }
  53800. vertex1.subtractToRef(vertex0, this._edge1);
  53801. vertex2.subtractToRef(vertex0, this._edge2);
  53802. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53803. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53804. if (det === 0) {
  53805. return null;
  53806. }
  53807. var invdet = 1 / det;
  53808. this.origin.subtractToRef(vertex0, this._tvec);
  53809. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53810. if (bu < 0 || bu > 1.0) {
  53811. return null;
  53812. }
  53813. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53814. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53815. if (bv < 0 || bu + bv > 1.0) {
  53816. return null;
  53817. }
  53818. //check if the distance is longer than the predefined length.
  53819. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53820. if (distance > this.length) {
  53821. return null;
  53822. }
  53823. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53824. };
  53825. Ray.prototype.intersectsPlane = function (plane) {
  53826. var distance;
  53827. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53828. if (Math.abs(result1) < 9.99999997475243E-07) {
  53829. return null;
  53830. }
  53831. else {
  53832. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53833. distance = (-plane.d - result2) / result1;
  53834. if (distance < 0.0) {
  53835. if (distance < -9.99999997475243E-07) {
  53836. return null;
  53837. }
  53838. else {
  53839. return 0;
  53840. }
  53841. }
  53842. return distance;
  53843. }
  53844. };
  53845. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53846. var tm = BABYLON.Tmp.Matrix[0];
  53847. mesh.getWorldMatrix().invertToRef(tm);
  53848. if (this._tmpRay) {
  53849. Ray.TransformToRef(this, tm, this._tmpRay);
  53850. }
  53851. else {
  53852. this._tmpRay = Ray.Transform(this, tm);
  53853. }
  53854. return mesh.intersects(this._tmpRay, fastCheck);
  53855. };
  53856. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53857. if (results) {
  53858. results.length = 0;
  53859. }
  53860. else {
  53861. results = [];
  53862. }
  53863. for (var i = 0; i < meshes.length; i++) {
  53864. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53865. if (pickInfo.hit) {
  53866. results.push(pickInfo);
  53867. }
  53868. }
  53869. results.sort(this._comparePickingInfo);
  53870. return results;
  53871. };
  53872. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53873. if (pickingInfoA.distance < pickingInfoB.distance) {
  53874. return -1;
  53875. }
  53876. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53877. return 1;
  53878. }
  53879. else {
  53880. return 0;
  53881. }
  53882. };
  53883. /**
  53884. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  53885. * @param sega the first point of the segment to test the intersection against
  53886. * @param segb the second point of the segment to test the intersection against
  53887. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  53888. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  53889. */
  53890. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  53891. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  53892. var u = segb.subtract(sega);
  53893. var v = rsegb.subtract(this.origin);
  53894. var w = sega.subtract(this.origin);
  53895. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  53896. var b = BABYLON.Vector3.Dot(u, v);
  53897. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  53898. var d = BABYLON.Vector3.Dot(u, w);
  53899. var e = BABYLON.Vector3.Dot(v, w);
  53900. var D = a * c - b * b; // always >= 0
  53901. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  53902. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  53903. // compute the line parameters of the two closest points
  53904. if (D < Ray.smallnum) { // the lines are almost parallel
  53905. sN = 0.0; // force using point P0 on segment S1
  53906. sD = 1.0; // to prevent possible division by 0.0 later
  53907. tN = e;
  53908. tD = c;
  53909. }
  53910. else { // get the closest points on the infinite lines
  53911. sN = (b * e - c * d);
  53912. tN = (a * e - b * d);
  53913. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  53914. sN = 0.0;
  53915. tN = e;
  53916. tD = c;
  53917. }
  53918. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  53919. sN = sD;
  53920. tN = e + b;
  53921. tD = c;
  53922. }
  53923. }
  53924. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  53925. tN = 0.0;
  53926. // recompute sc for this edge
  53927. if (-d < 0.0) {
  53928. sN = 0.0;
  53929. }
  53930. else if (-d > a)
  53931. sN = sD;
  53932. else {
  53933. sN = -d;
  53934. sD = a;
  53935. }
  53936. }
  53937. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  53938. tN = tD;
  53939. // recompute sc for this edge
  53940. if ((-d + b) < 0.0) {
  53941. sN = 0;
  53942. }
  53943. else if ((-d + b) > a) {
  53944. sN = sD;
  53945. }
  53946. else {
  53947. sN = (-d + b);
  53948. sD = a;
  53949. }
  53950. }
  53951. // finally do the division to get sc and tc
  53952. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  53953. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  53954. // get the difference of the two closest points
  53955. var qtc = v.multiplyByFloats(tc, tc, tc);
  53956. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  53957. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  53958. if (isIntersected) {
  53959. return qtc.length();
  53960. }
  53961. return -1;
  53962. };
  53963. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53964. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  53965. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  53966. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  53967. this.direction.normalize();
  53968. return this;
  53969. };
  53970. // Statics
  53971. Ray.Zero = function () {
  53972. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  53973. };
  53974. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53975. var result = Ray.Zero();
  53976. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  53977. };
  53978. /**
  53979. * 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
  53980. * transformed to the given world matrix.
  53981. * @param origin The origin point
  53982. * @param end The end point
  53983. * @param world a matrix to transform the ray to. Default is the identity matrix.
  53984. */
  53985. Ray.CreateNewFromTo = function (origin, end, world) {
  53986. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  53987. var direction = end.subtract(origin);
  53988. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  53989. direction.normalize();
  53990. return Ray.Transform(new Ray(origin, direction, length), world);
  53991. };
  53992. Ray.Transform = function (ray, matrix) {
  53993. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  53994. Ray.TransformToRef(ray, matrix, result);
  53995. return result;
  53996. };
  53997. Ray.TransformToRef = function (ray, matrix, result) {
  53998. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  53999. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54000. result.length = ray.length;
  54001. var dir = result.direction;
  54002. var len = dir.length();
  54003. if (!(len === 0 || len === 1)) {
  54004. var num = 1.0 / len;
  54005. dir.x *= num;
  54006. dir.y *= num;
  54007. dir.z *= num;
  54008. result.length *= len;
  54009. }
  54010. };
  54011. Ray.smallnum = 0.00000001;
  54012. Ray.rayl = 10e8;
  54013. return Ray;
  54014. }());
  54015. BABYLON.Ray = Ray;
  54016. })(BABYLON || (BABYLON = {}));
  54017. //# sourceMappingURL=babylon.ray.js.map
  54018. var BABYLON;
  54019. (function (BABYLON) {
  54020. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54021. if (boxMin.x > sphereCenter.x + sphereRadius)
  54022. return false;
  54023. if (sphereCenter.x - sphereRadius > boxMax.x)
  54024. return false;
  54025. if (boxMin.y > sphereCenter.y + sphereRadius)
  54026. return false;
  54027. if (sphereCenter.y - sphereRadius > boxMax.y)
  54028. return false;
  54029. if (boxMin.z > sphereCenter.z + sphereRadius)
  54030. return false;
  54031. if (sphereCenter.z - sphereRadius > boxMax.z)
  54032. return false;
  54033. return true;
  54034. };
  54035. var getLowestRoot = (function () {
  54036. var result = { root: 0, found: false };
  54037. return function (a, b, c, maxR) {
  54038. result.root = 0;
  54039. result.found = false;
  54040. var determinant = b * b - 4.0 * a * c;
  54041. if (determinant < 0)
  54042. return result;
  54043. var sqrtD = Math.sqrt(determinant);
  54044. var r1 = (-b - sqrtD) / (2.0 * a);
  54045. var r2 = (-b + sqrtD) / (2.0 * a);
  54046. if (r1 > r2) {
  54047. var temp = r2;
  54048. r2 = r1;
  54049. r1 = temp;
  54050. }
  54051. if (r1 > 0 && r1 < maxR) {
  54052. result.root = r1;
  54053. result.found = true;
  54054. return result;
  54055. }
  54056. if (r2 > 0 && r2 < maxR) {
  54057. result.root = r2;
  54058. result.found = true;
  54059. return result;
  54060. }
  54061. return result;
  54062. };
  54063. })();
  54064. var Collider = /** @class */ (function () {
  54065. function Collider() {
  54066. this._collisionPoint = BABYLON.Vector3.Zero();
  54067. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54068. this._tempVector = BABYLON.Vector3.Zero();
  54069. this._tempVector2 = BABYLON.Vector3.Zero();
  54070. this._tempVector3 = BABYLON.Vector3.Zero();
  54071. this._tempVector4 = BABYLON.Vector3.Zero();
  54072. this._edge = BABYLON.Vector3.Zero();
  54073. this._baseToVertex = BABYLON.Vector3.Zero();
  54074. this._destinationPoint = BABYLON.Vector3.Zero();
  54075. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54076. this._displacementVector = BABYLON.Vector3.Zero();
  54077. this._radius = BABYLON.Vector3.One();
  54078. this._retry = 0;
  54079. this._basePointWorld = BABYLON.Vector3.Zero();
  54080. this._velocityWorld = BABYLON.Vector3.Zero();
  54081. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54082. this._collisionMask = -1;
  54083. }
  54084. Object.defineProperty(Collider.prototype, "collisionMask", {
  54085. get: function () {
  54086. return this._collisionMask;
  54087. },
  54088. set: function (mask) {
  54089. this._collisionMask = !isNaN(mask) ? mask : -1;
  54090. },
  54091. enumerable: true,
  54092. configurable: true
  54093. });
  54094. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54095. /**
  54096. * Gets the plane normal used to compute the sliding response (in local space)
  54097. */
  54098. get: function () {
  54099. return this._slidePlaneNormal;
  54100. },
  54101. enumerable: true,
  54102. configurable: true
  54103. });
  54104. // Methods
  54105. Collider.prototype._initialize = function (source, dir, e) {
  54106. this._velocity = dir;
  54107. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54108. this._basePoint = source;
  54109. source.multiplyToRef(this._radius, this._basePointWorld);
  54110. dir.multiplyToRef(this._radius, this._velocityWorld);
  54111. this._velocityWorldLength = this._velocityWorld.length();
  54112. this._epsilon = e;
  54113. this.collisionFound = false;
  54114. };
  54115. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54116. pa.subtractToRef(point, this._tempVector);
  54117. pb.subtractToRef(point, this._tempVector2);
  54118. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54119. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54120. if (d < 0)
  54121. return false;
  54122. pc.subtractToRef(point, this._tempVector3);
  54123. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54124. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54125. if (d < 0)
  54126. return false;
  54127. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54128. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54129. return d >= 0;
  54130. };
  54131. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54132. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54133. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54134. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54135. return false;
  54136. }
  54137. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54138. return false;
  54139. return true;
  54140. };
  54141. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54142. var t0;
  54143. var embeddedInPlane = false;
  54144. //defensive programming, actually not needed.
  54145. if (!trianglePlaneArray) {
  54146. trianglePlaneArray = [];
  54147. }
  54148. if (!trianglePlaneArray[faceIndex]) {
  54149. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54150. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54151. }
  54152. var trianglePlane = trianglePlaneArray[faceIndex];
  54153. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54154. return;
  54155. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54156. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54157. if (normalDotVelocity == 0) {
  54158. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54159. return;
  54160. embeddedInPlane = true;
  54161. t0 = 0;
  54162. }
  54163. else {
  54164. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54165. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54166. if (t0 > t1) {
  54167. var temp = t1;
  54168. t1 = t0;
  54169. t0 = temp;
  54170. }
  54171. if (t0 > 1.0 || t1 < 0.0)
  54172. return;
  54173. if (t0 < 0)
  54174. t0 = 0;
  54175. if (t0 > 1.0)
  54176. t0 = 1.0;
  54177. }
  54178. this._collisionPoint.copyFromFloats(0, 0, 0);
  54179. var found = false;
  54180. var t = 1.0;
  54181. if (!embeddedInPlane) {
  54182. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54183. this._velocity.scaleToRef(t0, this._tempVector);
  54184. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54185. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54186. found = true;
  54187. t = t0;
  54188. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54189. }
  54190. }
  54191. if (!found) {
  54192. var velocitySquaredLength = this._velocity.lengthSquared();
  54193. var a = velocitySquaredLength;
  54194. this._basePoint.subtractToRef(p1, this._tempVector);
  54195. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54196. var c = this._tempVector.lengthSquared() - 1.0;
  54197. var lowestRoot = getLowestRoot(a, b, c, t);
  54198. if (lowestRoot.found) {
  54199. t = lowestRoot.root;
  54200. found = true;
  54201. this._collisionPoint.copyFrom(p1);
  54202. }
  54203. this._basePoint.subtractToRef(p2, this._tempVector);
  54204. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54205. c = this._tempVector.lengthSquared() - 1.0;
  54206. lowestRoot = getLowestRoot(a, b, c, t);
  54207. if (lowestRoot.found) {
  54208. t = lowestRoot.root;
  54209. found = true;
  54210. this._collisionPoint.copyFrom(p2);
  54211. }
  54212. this._basePoint.subtractToRef(p3, this._tempVector);
  54213. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54214. c = this._tempVector.lengthSquared() - 1.0;
  54215. lowestRoot = getLowestRoot(a, b, c, t);
  54216. if (lowestRoot.found) {
  54217. t = lowestRoot.root;
  54218. found = true;
  54219. this._collisionPoint.copyFrom(p3);
  54220. }
  54221. p2.subtractToRef(p1, this._edge);
  54222. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54223. var edgeSquaredLength = this._edge.lengthSquared();
  54224. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54225. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54226. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54227. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54228. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54229. lowestRoot = getLowestRoot(a, b, c, t);
  54230. if (lowestRoot.found) {
  54231. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54232. if (f >= 0.0 && f <= 1.0) {
  54233. t = lowestRoot.root;
  54234. found = true;
  54235. this._edge.scaleInPlace(f);
  54236. p1.addToRef(this._edge, this._collisionPoint);
  54237. }
  54238. }
  54239. p3.subtractToRef(p2, this._edge);
  54240. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54241. edgeSquaredLength = this._edge.lengthSquared();
  54242. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54243. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54244. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54245. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54246. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54247. lowestRoot = getLowestRoot(a, b, c, t);
  54248. if (lowestRoot.found) {
  54249. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54250. if (f >= 0.0 && f <= 1.0) {
  54251. t = lowestRoot.root;
  54252. found = true;
  54253. this._edge.scaleInPlace(f);
  54254. p2.addToRef(this._edge, this._collisionPoint);
  54255. }
  54256. }
  54257. p1.subtractToRef(p3, this._edge);
  54258. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54259. edgeSquaredLength = this._edge.lengthSquared();
  54260. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54261. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54262. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54263. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54264. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54265. lowestRoot = getLowestRoot(a, b, c, t);
  54266. if (lowestRoot.found) {
  54267. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54268. if (f >= 0.0 && f <= 1.0) {
  54269. t = lowestRoot.root;
  54270. found = true;
  54271. this._edge.scaleInPlace(f);
  54272. p3.addToRef(this._edge, this._collisionPoint);
  54273. }
  54274. }
  54275. }
  54276. if (found) {
  54277. var distToCollision = t * this._velocity.length();
  54278. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54279. if (!this.intersectionPoint) {
  54280. this.intersectionPoint = this._collisionPoint.clone();
  54281. }
  54282. else {
  54283. this.intersectionPoint.copyFrom(this._collisionPoint);
  54284. }
  54285. this._nearestDistance = distToCollision;
  54286. this.collisionFound = true;
  54287. }
  54288. }
  54289. };
  54290. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54291. for (var i = indexStart; i < indexEnd; i += 3) {
  54292. var p1 = pts[indices[i] - decal];
  54293. var p2 = pts[indices[i + 1] - decal];
  54294. var p3 = pts[indices[i + 2] - decal];
  54295. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54296. }
  54297. };
  54298. Collider.prototype._getResponse = function (pos, vel) {
  54299. pos.addToRef(vel, this._destinationPoint);
  54300. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54301. this._basePoint.addToRef(vel, pos);
  54302. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54303. this._slidePlaneNormal.normalize();
  54304. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54305. pos.addInPlace(this._displacementVector);
  54306. this.intersectionPoint.addInPlace(this._displacementVector);
  54307. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54308. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54309. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54310. };
  54311. return Collider;
  54312. }());
  54313. BABYLON.Collider = Collider;
  54314. })(BABYLON || (BABYLON = {}));
  54315. //# sourceMappingURL=babylon.collider.js.map
  54316. var BABYLON;
  54317. (function (BABYLON) {
  54318. //WebWorker code will be inserted to this variable.
  54319. BABYLON.CollisionWorker = "";
  54320. /** Defines supported task for worker process */
  54321. var WorkerTaskType;
  54322. (function (WorkerTaskType) {
  54323. /** Initialization */
  54324. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54325. /** Update of geometry */
  54326. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54327. /** Evaluate collision */
  54328. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54329. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54330. /** Defines kind of replies returned by worker */
  54331. var WorkerReplyType;
  54332. (function (WorkerReplyType) {
  54333. /** Success */
  54334. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54335. /** Unkown error */
  54336. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54337. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54338. var CollisionCoordinatorWorker = /** @class */ (function () {
  54339. function CollisionCoordinatorWorker() {
  54340. var _this = this;
  54341. this._scaledPosition = BABYLON.Vector3.Zero();
  54342. this._scaledVelocity = BABYLON.Vector3.Zero();
  54343. this.onMeshUpdated = function (transformNode) {
  54344. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54345. };
  54346. this.onGeometryUpdated = function (geometry) {
  54347. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54348. };
  54349. this._afterRender = function () {
  54350. if (!_this._init)
  54351. return;
  54352. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54353. return;
  54354. }
  54355. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54356. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54357. if (_this._runningUpdated > 4) {
  54358. return;
  54359. }
  54360. ++_this._runningUpdated;
  54361. var payload = {
  54362. updatedMeshes: _this._addUpdateMeshesList,
  54363. updatedGeometries: _this._addUpdateGeometriesList,
  54364. removedGeometries: _this._toRemoveGeometryArray,
  54365. removedMeshes: _this._toRemoveMeshesArray
  54366. };
  54367. var message = {
  54368. payload: payload,
  54369. taskType: WorkerTaskType.UPDATE
  54370. };
  54371. var serializable = [];
  54372. for (var id in payload.updatedGeometries) {
  54373. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54374. //prepare transferables
  54375. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54376. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54377. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54378. }
  54379. }
  54380. _this._worker.postMessage(message, serializable);
  54381. _this._addUpdateMeshesList = {};
  54382. _this._addUpdateGeometriesList = {};
  54383. _this._toRemoveGeometryArray = [];
  54384. _this._toRemoveMeshesArray = [];
  54385. };
  54386. this._onMessageFromWorker = function (e) {
  54387. var returnData = e.data;
  54388. if (returnData.error != WorkerReplyType.SUCCESS) {
  54389. //TODO what errors can be returned from the worker?
  54390. BABYLON.Tools.Warn("error returned from worker!");
  54391. return;
  54392. }
  54393. switch (returnData.taskType) {
  54394. case WorkerTaskType.INIT:
  54395. _this._init = true;
  54396. //Update the worked with ALL of the scene's current state
  54397. _this._scene.meshes.forEach(function (mesh) {
  54398. _this.onMeshAdded(mesh);
  54399. });
  54400. _this._scene.getGeometries().forEach(function (geometry) {
  54401. _this.onGeometryAdded(geometry);
  54402. });
  54403. break;
  54404. case WorkerTaskType.UPDATE:
  54405. _this._runningUpdated--;
  54406. break;
  54407. case WorkerTaskType.COLLIDE:
  54408. var returnPayload = returnData.payload;
  54409. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54410. return;
  54411. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54412. if (callback) {
  54413. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54414. if (mesh) {
  54415. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54416. }
  54417. }
  54418. //cleanup
  54419. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54420. break;
  54421. }
  54422. };
  54423. this._collisionsCallbackArray = [];
  54424. this._init = false;
  54425. this._runningUpdated = 0;
  54426. this._addUpdateMeshesList = {};
  54427. this._addUpdateGeometriesList = {};
  54428. this._toRemoveGeometryArray = [];
  54429. this._toRemoveMeshesArray = [];
  54430. }
  54431. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54432. if (!this._init)
  54433. return;
  54434. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54435. return;
  54436. position.divideToRef(collider._radius, this._scaledPosition);
  54437. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54438. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54439. var payload = {
  54440. collider: {
  54441. position: this._scaledPosition.asArray(),
  54442. velocity: this._scaledVelocity.asArray(),
  54443. radius: collider._radius.asArray()
  54444. },
  54445. collisionId: collisionIndex,
  54446. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54447. maximumRetry: maximumRetry
  54448. };
  54449. var message = {
  54450. payload: payload,
  54451. taskType: WorkerTaskType.COLLIDE
  54452. };
  54453. this._worker.postMessage(message);
  54454. };
  54455. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54456. this._scene = scene;
  54457. this._scene.registerAfterRender(this._afterRender);
  54458. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54459. this._worker = new Worker(workerUrl);
  54460. this._worker.onmessage = this._onMessageFromWorker;
  54461. var message = {
  54462. payload: {},
  54463. taskType: WorkerTaskType.INIT
  54464. };
  54465. this._worker.postMessage(message);
  54466. };
  54467. CollisionCoordinatorWorker.prototype.destroy = function () {
  54468. this._scene.unregisterAfterRender(this._afterRender);
  54469. this._worker.terminate();
  54470. };
  54471. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54472. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54473. this.onMeshUpdated(mesh);
  54474. };
  54475. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54476. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54477. };
  54478. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54479. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54480. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54481. this.onGeometryUpdated(geometry);
  54482. };
  54483. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54484. this._toRemoveGeometryArray.push(geometry.id);
  54485. };
  54486. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54487. var submeshes = [];
  54488. if (mesh.subMeshes) {
  54489. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54490. var boundingInfo = sm.getBoundingInfo();
  54491. return {
  54492. position: idx,
  54493. verticesStart: sm.verticesStart,
  54494. verticesCount: sm.verticesCount,
  54495. indexStart: sm.indexStart,
  54496. indexCount: sm.indexCount,
  54497. hasMaterial: !!sm.getMaterial(),
  54498. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54499. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54500. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54501. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54502. };
  54503. });
  54504. }
  54505. var geometryId = null;
  54506. if (mesh instanceof BABYLON.Mesh) {
  54507. var geometry = mesh.geometry;
  54508. geometryId = geometry ? geometry.id : null;
  54509. }
  54510. else if (mesh instanceof BABYLON.InstancedMesh) {
  54511. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54512. geometryId = geometry ? geometry.id : null;
  54513. }
  54514. var boundingInfo = mesh.getBoundingInfo();
  54515. return {
  54516. uniqueId: mesh.uniqueId,
  54517. id: mesh.id,
  54518. name: mesh.name,
  54519. geometryId: geometryId,
  54520. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54521. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54522. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54523. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54524. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54525. subMeshes: submeshes,
  54526. checkCollisions: mesh.checkCollisions
  54527. };
  54528. };
  54529. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54530. return {
  54531. id: geometry.id,
  54532. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54533. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54534. indices: new Uint32Array(geometry.getIndices() || []),
  54535. };
  54536. };
  54537. return CollisionCoordinatorWorker;
  54538. }());
  54539. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54540. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54541. function CollisionCoordinatorLegacy() {
  54542. this._scaledPosition = BABYLON.Vector3.Zero();
  54543. this._scaledVelocity = BABYLON.Vector3.Zero();
  54544. this._finalPosition = BABYLON.Vector3.Zero();
  54545. }
  54546. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54547. position.divideToRef(collider._radius, this._scaledPosition);
  54548. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54549. collider.collidedMesh = null;
  54550. collider._retry = 0;
  54551. collider._initialVelocity = this._scaledVelocity;
  54552. collider._initialPosition = this._scaledPosition;
  54553. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54554. this._finalPosition.multiplyInPlace(collider._radius);
  54555. //run the callback
  54556. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54557. };
  54558. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54559. this._scene = scene;
  54560. };
  54561. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54562. //Legacy need no destruction method.
  54563. };
  54564. //No update in legacy mode
  54565. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54566. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54567. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54568. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54569. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54570. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54571. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54572. if (excludedMesh === void 0) { excludedMesh = null; }
  54573. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54574. if (collider._retry >= maximumRetry) {
  54575. finalPosition.copyFrom(position);
  54576. return;
  54577. }
  54578. // Check if this is a mesh else camera or -1
  54579. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54580. collider._initialize(position, velocity, closeDistance);
  54581. // Check all meshes
  54582. for (var index = 0; index < this._scene.meshes.length; index++) {
  54583. var mesh = this._scene.meshes[index];
  54584. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54585. mesh._checkCollision(collider);
  54586. }
  54587. }
  54588. if (!collider.collisionFound) {
  54589. position.addToRef(velocity, finalPosition);
  54590. return;
  54591. }
  54592. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54593. collider._getResponse(position, velocity);
  54594. }
  54595. if (velocity.length() <= closeDistance) {
  54596. finalPosition.copyFrom(position);
  54597. return;
  54598. }
  54599. collider._retry++;
  54600. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54601. };
  54602. return CollisionCoordinatorLegacy;
  54603. }());
  54604. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54605. })(BABYLON || (BABYLON = {}));
  54606. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54607. var BABYLON;
  54608. (function (BABYLON) {
  54609. /**
  54610. * A particle represents one of the element emitted by a particle system.
  54611. * This is mainly define by its coordinates, direction, velocity and age.
  54612. */
  54613. var Particle = /** @class */ (function () {
  54614. /**
  54615. * Creates a new instance Particle
  54616. * @param particleSystem the particle system the particle belongs to
  54617. */
  54618. function Particle(
  54619. /**
  54620. * particleSystem the particle system the particle belongs to.
  54621. */
  54622. particleSystem) {
  54623. this.particleSystem = particleSystem;
  54624. /**
  54625. * The world position of the particle in the scene.
  54626. */
  54627. this.position = BABYLON.Vector3.Zero();
  54628. /**
  54629. * The world direction of the particle in the scene.
  54630. */
  54631. this.direction = BABYLON.Vector3.Zero();
  54632. /**
  54633. * The color of the particle.
  54634. */
  54635. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54636. /**
  54637. * The color change of the particle per step.
  54638. */
  54639. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54640. /**
  54641. * Defines how long will the life of the particle be.
  54642. */
  54643. this.lifeTime = 1.0;
  54644. /**
  54645. * The current age of the particle.
  54646. */
  54647. this.age = 0;
  54648. /**
  54649. * The current size of the particle.
  54650. */
  54651. this.size = 0;
  54652. /**
  54653. * The current scale of the particle.
  54654. */
  54655. this.scale = new BABYLON.Vector2(1, 1);
  54656. /**
  54657. * The current angle of the particle.
  54658. */
  54659. this.angle = 0;
  54660. /**
  54661. * Defines how fast is the angle changing.
  54662. */
  54663. this.angularSpeed = 0;
  54664. /**
  54665. * Defines the cell index used by the particle to be rendered from a sprite.
  54666. */
  54667. this.cellIndex = 0;
  54668. /** @hidden */
  54669. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54670. /** @hidden */
  54671. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54672. /** @hidden */
  54673. this._currentSize1 = 0;
  54674. /** @hidden */
  54675. this._currentSize2 = 0;
  54676. /** @hidden */
  54677. this._currentAngularSpeed1 = 0;
  54678. /** @hidden */
  54679. this._currentAngularSpeed2 = 0;
  54680. /** @hidden */
  54681. this._currentVelocity1 = 0;
  54682. /** @hidden */
  54683. this._currentVelocity2 = 0;
  54684. if (!this.particleSystem.isAnimationSheetEnabled) {
  54685. return;
  54686. }
  54687. this.updateCellInfoFromSystem();
  54688. }
  54689. Particle.prototype.updateCellInfoFromSystem = function () {
  54690. this.cellIndex = this.particleSystem.startSpriteCellID;
  54691. };
  54692. /**
  54693. * Defines how the sprite cell index is updated for the particle
  54694. */
  54695. Particle.prototype.updateCellIndex = function () {
  54696. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  54697. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  54698. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  54699. };
  54700. /**
  54701. * Copy the properties of particle to another one.
  54702. * @param other the particle to copy the information to.
  54703. */
  54704. Particle.prototype.copyTo = function (other) {
  54705. other.position.copyFrom(this.position);
  54706. if (this._initialDirection) {
  54707. if (other._initialDirection) {
  54708. other._initialDirection.copyFrom(this._initialDirection);
  54709. }
  54710. else {
  54711. other._initialDirection = this._initialDirection.clone();
  54712. }
  54713. }
  54714. else {
  54715. other._initialDirection = null;
  54716. }
  54717. other.direction.copyFrom(this.direction);
  54718. other.color.copyFrom(this.color);
  54719. other.colorStep.copyFrom(this.colorStep);
  54720. other.lifeTime = this.lifeTime;
  54721. other.age = this.age;
  54722. other.size = this.size;
  54723. other.scale.copyFrom(this.scale);
  54724. other.angle = this.angle;
  54725. other.angularSpeed = this.angularSpeed;
  54726. other.particleSystem = this.particleSystem;
  54727. other.cellIndex = this.cellIndex;
  54728. if (this._currentColorGradient) {
  54729. other._currentColorGradient = this._currentColorGradient;
  54730. other._currentColor1.copyFrom(this._currentColor1);
  54731. other._currentColor2.copyFrom(this._currentColor2);
  54732. }
  54733. if (this._currentSizeGradient) {
  54734. other._currentSizeGradient = this._currentSizeGradient;
  54735. other._currentSize1 = this._currentSize1;
  54736. other._currentSize2 = this._currentSize2;
  54737. }
  54738. if (this._currentAngularSpeedGradient) {
  54739. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  54740. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  54741. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  54742. }
  54743. if (this._currentVelocityGradient) {
  54744. other._currentVelocityGradient = this._currentVelocityGradient;
  54745. other._currentVelocity1 = this._currentVelocity1;
  54746. other._currentVelocity2 = this._currentVelocity2;
  54747. }
  54748. if (this.particleSystem.isAnimationSheetEnabled) {
  54749. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  54750. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  54751. }
  54752. };
  54753. return Particle;
  54754. }());
  54755. BABYLON.Particle = Particle;
  54756. })(BABYLON || (BABYLON = {}));
  54757. //# sourceMappingURL=babylon.particle.js.map
  54758. var BABYLON;
  54759. (function (BABYLON) {
  54760. /**
  54761. * This represents a particle system in Babylon.
  54762. * 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.
  54763. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54764. * @example https://doc.babylonjs.com/babylon101/particles
  54765. */
  54766. var ParticleSystem = /** @class */ (function () {
  54767. /**
  54768. * Instantiates a particle system.
  54769. * 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.
  54770. * @param name The name of the particle system
  54771. * @param capacity The max number of particles alive at the same time
  54772. * @param scene The scene the particle system belongs to
  54773. * @param customEffect a custom effect used to change the way particles are rendered by default
  54774. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54775. * @param epsilon Offset used to render the particles
  54776. */
  54777. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54778. if (customEffect === void 0) { customEffect = null; }
  54779. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54780. if (epsilon === void 0) { epsilon = 0.01; }
  54781. var _this = this;
  54782. /**
  54783. * List of animations used by the particle system.
  54784. */
  54785. this.animations = [];
  54786. /**
  54787. * The rendering group used by the Particle system to chose when to render.
  54788. */
  54789. this.renderingGroupId = 0;
  54790. /**
  54791. * The emitter represents the Mesh or position we are attaching the particle system to.
  54792. */
  54793. this.emitter = null;
  54794. /**
  54795. * The maximum number of particles to emit per frame
  54796. */
  54797. this.emitRate = 10;
  54798. /**
  54799. * If you want to launch only a few particles at once, that can be done, as well.
  54800. */
  54801. this.manualEmitCount = -1;
  54802. /**
  54803. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54804. */
  54805. this.updateSpeed = 0.01;
  54806. /**
  54807. * The amount of time the particle system is running (depends of the overall update speed).
  54808. */
  54809. this.targetStopDuration = 0;
  54810. /**
  54811. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54812. */
  54813. this.disposeOnStop = false;
  54814. /**
  54815. * Minimum power of emitting particles.
  54816. */
  54817. this.minEmitPower = 1;
  54818. /**
  54819. * Maximum power of emitting particles.
  54820. */
  54821. this.maxEmitPower = 1;
  54822. /**
  54823. * Minimum life time of emitting particles.
  54824. */
  54825. this.minLifeTime = 1;
  54826. /**
  54827. * Maximum life time of emitting particles.
  54828. */
  54829. this.maxLifeTime = 1;
  54830. /**
  54831. * Minimum Size of emitting particles.
  54832. */
  54833. this.minSize = 1;
  54834. /**
  54835. * Maximum Size of emitting particles.
  54836. */
  54837. this.maxSize = 1;
  54838. /**
  54839. * Minimum scale of emitting particles on X axis.
  54840. */
  54841. this.minScaleX = 1;
  54842. /**
  54843. * Maximum scale of emitting particles on X axis.
  54844. */
  54845. this.maxScaleX = 1;
  54846. /**
  54847. * Minimum scale of emitting particles on Y axis.
  54848. */
  54849. this.minScaleY = 1;
  54850. /**
  54851. * Maximum scale of emitting particles on Y axis.
  54852. */
  54853. this.maxScaleY = 1;
  54854. /**
  54855. * Gets or sets the minimal initial rotation in radians.
  54856. */
  54857. this.minInitialRotation = 0;
  54858. /**
  54859. * Gets or sets the maximal initial rotation in radians.
  54860. */
  54861. this.maxInitialRotation = 0;
  54862. /**
  54863. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54864. */
  54865. this.minAngularSpeed = 0;
  54866. /**
  54867. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54868. */
  54869. this.maxAngularSpeed = 0;
  54870. /**
  54871. * The layer mask we are rendering the particles through.
  54872. */
  54873. this.layerMask = 0x0FFFFFFF;
  54874. /**
  54875. * This can help using your own shader to render the particle system.
  54876. * The according effect will be created
  54877. */
  54878. this.customShader = null;
  54879. /**
  54880. * By default particle system starts as soon as they are created. This prevents the
  54881. * automatic start to happen and let you decide when to start emitting particles.
  54882. */
  54883. this.preventAutoStart = false;
  54884. /**
  54885. * Callback triggered when the particle animation is ending.
  54886. */
  54887. this.onAnimationEnd = null;
  54888. /**
  54889. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  54890. */
  54891. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  54892. /**
  54893. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  54894. * to override the particles.
  54895. */
  54896. this.forceDepthWrite = false;
  54897. /**
  54898. * You can use gravity if you want to give an orientation to your particles.
  54899. */
  54900. this.gravity = BABYLON.Vector3.Zero();
  54901. this._colorGradients = null;
  54902. this._sizeGradients = null;
  54903. this._lifeTimeGradients = null;
  54904. this._angularSpeedGradients = null;
  54905. this._velocityGradients = null;
  54906. /**
  54907. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  54908. */
  54909. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54910. /**
  54911. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  54912. */
  54913. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54914. /**
  54915. * Color the particle will have at the end of its lifetime
  54916. */
  54917. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  54918. /**
  54919. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  54920. */
  54921. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54922. /**
  54923. * 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)
  54924. */
  54925. this.spriteCellChangeSpeed = 1;
  54926. /**
  54927. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  54928. */
  54929. this.startSpriteCellID = 0;
  54930. /**
  54931. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  54932. */
  54933. this.endSpriteCellID = 0;
  54934. /**
  54935. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  54936. */
  54937. this.spriteCellWidth = 0;
  54938. /**
  54939. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  54940. */
  54941. this.spriteCellHeight = 0;
  54942. /** 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 */
  54943. this.preWarmCycles = 0;
  54944. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  54945. this.preWarmStepOffset = 1;
  54946. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  54947. this.translationPivot = new BABYLON.Vector2(0, 0);
  54948. /**
  54949. * An event triggered when the system is disposed
  54950. */
  54951. this.onDisposeObservable = new BABYLON.Observable();
  54952. /**
  54953. * Gets or sets the billboard mode to use when isBillboardBased = true.
  54954. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  54955. */
  54956. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  54957. this._particles = new Array();
  54958. this._stockParticles = new Array();
  54959. this._newPartsExcess = 0;
  54960. this._vertexBuffers = {};
  54961. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  54962. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  54963. this._scaledDirection = BABYLON.Vector3.Zero();
  54964. this._scaledGravity = BABYLON.Vector3.Zero();
  54965. this._currentRenderId = -1;
  54966. this._useInstancing = false;
  54967. this._started = false;
  54968. this._stopped = false;
  54969. this._actualFrame = 0;
  54970. this._isBillboardBased = true;
  54971. // start of sub system methods
  54972. /**
  54973. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  54974. * Its lifetime will start back at 0.
  54975. */
  54976. this.recycleParticle = function (particle) {
  54977. var lastParticle = _this._particles.pop();
  54978. if (lastParticle !== particle) {
  54979. lastParticle.copyTo(particle);
  54980. }
  54981. _this._stockParticles.push(lastParticle);
  54982. };
  54983. this._createParticle = function () {
  54984. var particle;
  54985. if (_this._stockParticles.length !== 0) {
  54986. particle = _this._stockParticles.pop();
  54987. particle.age = 0;
  54988. particle._currentColorGradient = null;
  54989. particle.cellIndex = _this.startSpriteCellID;
  54990. }
  54991. else {
  54992. particle = new BABYLON.Particle(_this);
  54993. }
  54994. return particle;
  54995. };
  54996. this._emitFromParticle = function (particle) {
  54997. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  54998. return;
  54999. }
  55000. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55001. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55002. subSystem._rootParticleSystem = _this;
  55003. _this.activeSubSystems.push(subSystem);
  55004. subSystem.start();
  55005. };
  55006. this.id = name;
  55007. this.name = name;
  55008. this._capacity = capacity;
  55009. this._epsilon = epsilon;
  55010. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55011. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55012. this._customEffect = customEffect;
  55013. scene.particleSystems.push(this);
  55014. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55015. this._createIndexBuffer();
  55016. this._createVertexBuffers();
  55017. // Default emitter type
  55018. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55019. this.updateFunction = function (particles) {
  55020. var _loop_1 = function () {
  55021. particle = particles[index];
  55022. particle.age += _this._scaledUpdateSpeed;
  55023. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55024. _this._emitFromParticle(particle);
  55025. _this.recycleParticle(particle);
  55026. index--;
  55027. return "continue";
  55028. }
  55029. else {
  55030. var ratio = particle.age / particle.lifeTime;
  55031. // Color
  55032. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55033. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55034. if (currentGradient !== particle._currentColorGradient) {
  55035. particle._currentColor1.copyFrom(particle._currentColor2);
  55036. nextGradient.getColorToRef(particle._currentColor2);
  55037. particle._currentColorGradient = currentGradient;
  55038. }
  55039. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55040. });
  55041. }
  55042. else {
  55043. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55044. particle.color.addInPlace(_this._scaledColorStep);
  55045. if (particle.color.a < 0) {
  55046. particle.color.a = 0;
  55047. }
  55048. }
  55049. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  55050. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  55051. if (currentGradient !== particle._currentAngularSpeedGradient) {
  55052. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  55053. particle._currentAngularSpeed2 = nextGradient.getFactor();
  55054. particle._currentAngularSpeedGradient = currentGradient;
  55055. }
  55056. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  55057. });
  55058. }
  55059. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55060. var directionScale_1 = _this._scaledUpdateSpeed;
  55061. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  55062. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  55063. if (currentGradient !== particle._currentVelocityGradient) {
  55064. particle._currentVelocity1 = particle._currentVelocity2;
  55065. particle._currentVelocity2 = nextGradient.getFactor();
  55066. particle._currentVelocityGradient = currentGradient;
  55067. }
  55068. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  55069. });
  55070. }
  55071. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  55072. particle.position.addInPlace(_this._scaledDirection);
  55073. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55074. particle.direction.addInPlace(_this._scaledGravity);
  55075. // Size
  55076. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55077. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55078. if (currentGradient !== particle._currentSizeGradient) {
  55079. particle._currentSize1 = particle._currentSize2;
  55080. particle._currentSize2 = nextGradient.getFactor();
  55081. particle._currentSizeGradient = currentGradient;
  55082. }
  55083. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  55084. });
  55085. }
  55086. if (_this._isAnimationSheetEnabled) {
  55087. particle.updateCellIndex();
  55088. }
  55089. }
  55090. };
  55091. var particle;
  55092. for (var index = 0; index < particles.length; index++) {
  55093. _loop_1();
  55094. }
  55095. };
  55096. }
  55097. /**
  55098. * Gets the current list of color gradients.
  55099. * You must use addColorGradient and removeColorGradient to udpate this list
  55100. * @returns the list of color gradients
  55101. */
  55102. ParticleSystem.prototype.getColorGradients = function () {
  55103. return this._colorGradients;
  55104. };
  55105. /**
  55106. * Gets the current list of size gradients.
  55107. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55108. * @returns the list of size gradients
  55109. */
  55110. ParticleSystem.prototype.getSizeGradients = function () {
  55111. return this._sizeGradients;
  55112. };
  55113. /**
  55114. * Gets the current list of life time gradients.
  55115. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55116. * @returns the list of life time gradients
  55117. */
  55118. ParticleSystem.prototype.getLifeTimeGradients = function () {
  55119. return this._lifeTimeGradients;
  55120. };
  55121. /**
  55122. * Gets the current list of angular speed gradients.
  55123. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55124. * @returns the list of angular speed gradients
  55125. */
  55126. ParticleSystem.prototype.getAngularSpeedGradients = function () {
  55127. return this._angularSpeedGradients;
  55128. };
  55129. /**
  55130. * Gets the current list of velocity gradients.
  55131. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55132. * @returns the list of velocity gradients
  55133. */
  55134. ParticleSystem.prototype.getVelocityGradients = function () {
  55135. return this._velocityGradients;
  55136. };
  55137. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55138. /**
  55139. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55140. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55141. */
  55142. get: function () {
  55143. if (this.particleEmitterType.direction1) {
  55144. return this.particleEmitterType.direction1;
  55145. }
  55146. return BABYLON.Vector3.Zero();
  55147. },
  55148. set: function (value) {
  55149. if (this.particleEmitterType.direction1) {
  55150. this.particleEmitterType.direction1 = value;
  55151. }
  55152. },
  55153. enumerable: true,
  55154. configurable: true
  55155. });
  55156. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55157. /**
  55158. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55159. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55160. */
  55161. get: function () {
  55162. if (this.particleEmitterType.direction2) {
  55163. return this.particleEmitterType.direction2;
  55164. }
  55165. return BABYLON.Vector3.Zero();
  55166. },
  55167. set: function (value) {
  55168. if (this.particleEmitterType.direction2) {
  55169. this.particleEmitterType.direction2 = value;
  55170. }
  55171. },
  55172. enumerable: true,
  55173. configurable: true
  55174. });
  55175. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55176. /**
  55177. * 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.
  55178. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55179. */
  55180. get: function () {
  55181. if (this.particleEmitterType.minEmitBox) {
  55182. return this.particleEmitterType.minEmitBox;
  55183. }
  55184. return BABYLON.Vector3.Zero();
  55185. },
  55186. set: function (value) {
  55187. if (this.particleEmitterType.minEmitBox) {
  55188. this.particleEmitterType.minEmitBox = value;
  55189. }
  55190. },
  55191. enumerable: true,
  55192. configurable: true
  55193. });
  55194. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55195. /**
  55196. * 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.
  55197. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55198. */
  55199. get: function () {
  55200. if (this.particleEmitterType.maxEmitBox) {
  55201. return this.particleEmitterType.maxEmitBox;
  55202. }
  55203. return BABYLON.Vector3.Zero();
  55204. },
  55205. set: function (value) {
  55206. if (this.particleEmitterType.maxEmitBox) {
  55207. this.particleEmitterType.maxEmitBox = value;
  55208. }
  55209. },
  55210. enumerable: true,
  55211. configurable: true
  55212. });
  55213. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55214. /**
  55215. * Sets a callback that will be triggered when the system is disposed
  55216. */
  55217. set: function (callback) {
  55218. if (this._onDisposeObserver) {
  55219. this.onDisposeObservable.remove(this._onDisposeObserver);
  55220. }
  55221. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55222. },
  55223. enumerable: true,
  55224. configurable: true
  55225. });
  55226. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55227. /**
  55228. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55229. */
  55230. get: function () {
  55231. return this._isAnimationSheetEnabled;
  55232. },
  55233. enumerable: true,
  55234. configurable: true
  55235. });
  55236. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55237. /**
  55238. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55239. */
  55240. get: function () {
  55241. return this._isBillboardBased;
  55242. },
  55243. set: function (value) {
  55244. if (this._isBillboardBased === value) {
  55245. return;
  55246. }
  55247. this._isBillboardBased = value;
  55248. this._resetEffect();
  55249. },
  55250. enumerable: true,
  55251. configurable: true
  55252. });
  55253. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55254. //end of Sub-emitter
  55255. /**
  55256. * Gets the current list of active particles
  55257. */
  55258. get: function () {
  55259. return this._particles;
  55260. },
  55261. enumerable: true,
  55262. configurable: true
  55263. });
  55264. /**
  55265. * Returns the string "ParticleSystem"
  55266. * @returns a string containing the class name
  55267. */
  55268. ParticleSystem.prototype.getClassName = function () {
  55269. return "ParticleSystem";
  55270. };
  55271. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55272. var newGradient = new BABYLON.FactorGradient();
  55273. newGradient.gradient = gradient;
  55274. newGradient.factor1 = factor;
  55275. newGradient.factor2 = factor2;
  55276. factorGradients.push(newGradient);
  55277. factorGradients.sort(function (a, b) {
  55278. if (a.gradient < b.gradient) {
  55279. return -1;
  55280. }
  55281. else if (a.gradient > b.gradient) {
  55282. return 1;
  55283. }
  55284. return 0;
  55285. });
  55286. };
  55287. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55288. if (!factorGradients) {
  55289. return;
  55290. }
  55291. var index = 0;
  55292. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55293. var factorGradient = factorGradients_1[_i];
  55294. if (factorGradient.gradient === gradient) {
  55295. factorGradients.splice(index, 1);
  55296. break;
  55297. }
  55298. index++;
  55299. }
  55300. };
  55301. /**
  55302. * Adds a new life time gradient
  55303. * @param gradient defines the gradient to use (between 0 and 1)
  55304. * @param factor defines the life time factor to affect to the specified gradient
  55305. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55306. * @returns the current particle system
  55307. */
  55308. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55309. if (!this._lifeTimeGradients) {
  55310. this._lifeTimeGradients = [];
  55311. }
  55312. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55313. return this;
  55314. };
  55315. /**
  55316. * Remove a specific life time gradient
  55317. * @param gradient defines the gradient to remove
  55318. * @returns the current particle system
  55319. */
  55320. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55321. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55322. return this;
  55323. };
  55324. /**
  55325. * Adds a new size gradient
  55326. * @param gradient defines the gradient to use (between 0 and 1)
  55327. * @param factor defines the size factor to affect to the specified gradient
  55328. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55329. * @returns the current particle system
  55330. */
  55331. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55332. if (!this._sizeGradients) {
  55333. this._sizeGradients = [];
  55334. }
  55335. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55336. return this;
  55337. };
  55338. /**
  55339. * Remove a specific size gradient
  55340. * @param gradient defines the gradient to remove
  55341. * @returns the current particle system
  55342. */
  55343. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55344. this._removeFactorGradient(this._sizeGradients, gradient);
  55345. return this;
  55346. };
  55347. /**
  55348. * Adds a new angular speed gradient
  55349. * @param gradient defines the gradient to use (between 0 and 1)
  55350. * @param factor defines the size factor to affect to the specified gradient
  55351. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55352. * @returns the current particle system
  55353. */
  55354. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  55355. if (!this._angularSpeedGradients) {
  55356. this._angularSpeedGradients = [];
  55357. }
  55358. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  55359. return this;
  55360. };
  55361. /**
  55362. * Remove a specific angular speed gradient
  55363. * @param gradient defines the gradient to remove
  55364. * @returns the current particle system
  55365. */
  55366. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  55367. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  55368. return this;
  55369. };
  55370. /**
  55371. * Adds a new velocity gradient
  55372. * @param gradient defines the gradient to use (between 0 and 1)
  55373. * @param factor defines the size factor to affect to the specified gradient
  55374. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55375. * @returns the current particle system
  55376. */
  55377. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  55378. if (!this._velocityGradients) {
  55379. this._velocityGradients = [];
  55380. }
  55381. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  55382. return this;
  55383. };
  55384. /**
  55385. * Remove a specific velocity gradient
  55386. * @param gradient defines the gradient to remove
  55387. * @returns the current particle system
  55388. */
  55389. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  55390. this._removeFactorGradient(this._velocityGradients, gradient);
  55391. return this;
  55392. };
  55393. /**
  55394. * Adds a new color gradient
  55395. * @param gradient defines the gradient to use (between 0 and 1)
  55396. * @param color defines the color to affect to the specified gradient
  55397. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55398. */
  55399. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55400. if (!this._colorGradients) {
  55401. this._colorGradients = [];
  55402. }
  55403. var colorGradient = new BABYLON.ColorGradient();
  55404. colorGradient.gradient = gradient;
  55405. colorGradient.color1 = color;
  55406. colorGradient.color2 = color2;
  55407. this._colorGradients.push(colorGradient);
  55408. this._colorGradients.sort(function (a, b) {
  55409. if (a.gradient < b.gradient) {
  55410. return -1;
  55411. }
  55412. else if (a.gradient > b.gradient) {
  55413. return 1;
  55414. }
  55415. return 0;
  55416. });
  55417. return this;
  55418. };
  55419. /**
  55420. * Remove a specific color gradient
  55421. * @param gradient defines the gradient to remove
  55422. */
  55423. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55424. if (!this._colorGradients) {
  55425. return this;
  55426. }
  55427. var index = 0;
  55428. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55429. var colorGradient = _a[_i];
  55430. if (colorGradient.gradient === gradient) {
  55431. this._colorGradients.splice(index, 1);
  55432. break;
  55433. }
  55434. index++;
  55435. }
  55436. return this;
  55437. };
  55438. ParticleSystem.prototype._resetEffect = function () {
  55439. if (this._vertexBuffer) {
  55440. this._vertexBuffer.dispose();
  55441. this._vertexBuffer = null;
  55442. }
  55443. if (this._spriteBuffer) {
  55444. this._spriteBuffer.dispose();
  55445. this._spriteBuffer = null;
  55446. }
  55447. this._createVertexBuffers();
  55448. };
  55449. ParticleSystem.prototype._createVertexBuffers = function () {
  55450. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55451. if (this._isAnimationSheetEnabled) {
  55452. this._vertexBufferSize += 1;
  55453. }
  55454. if (!this._isBillboardBased) {
  55455. this._vertexBufferSize += 3;
  55456. }
  55457. var engine = this._scene.getEngine();
  55458. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55459. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55460. var dataOffset = 0;
  55461. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55462. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55463. dataOffset += 3;
  55464. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55465. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55466. dataOffset += 4;
  55467. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55468. this._vertexBuffers["angle"] = options;
  55469. dataOffset += 1;
  55470. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55471. this._vertexBuffers["size"] = size;
  55472. dataOffset += 2;
  55473. if (this._isAnimationSheetEnabled) {
  55474. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55475. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55476. dataOffset += 1;
  55477. }
  55478. if (!this._isBillboardBased) {
  55479. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55480. this._vertexBuffers["direction"] = directionBuffer;
  55481. dataOffset += 3;
  55482. }
  55483. var offsets;
  55484. if (this._useInstancing) {
  55485. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55486. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55487. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55488. }
  55489. else {
  55490. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55491. dataOffset += 2;
  55492. }
  55493. this._vertexBuffers["offset"] = offsets;
  55494. };
  55495. ParticleSystem.prototype._createIndexBuffer = function () {
  55496. if (this._useInstancing) {
  55497. return;
  55498. }
  55499. var indices = [];
  55500. var index = 0;
  55501. for (var count = 0; count < this._capacity; count++) {
  55502. indices.push(index);
  55503. indices.push(index + 1);
  55504. indices.push(index + 2);
  55505. indices.push(index);
  55506. indices.push(index + 2);
  55507. indices.push(index + 3);
  55508. index += 4;
  55509. }
  55510. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55511. };
  55512. /**
  55513. * Gets the maximum number of particles active at the same time.
  55514. * @returns The max number of active particles.
  55515. */
  55516. ParticleSystem.prototype.getCapacity = function () {
  55517. return this._capacity;
  55518. };
  55519. /**
  55520. * Gets Wether there are still active particles in the system.
  55521. * @returns True if it is alive, otherwise false.
  55522. */
  55523. ParticleSystem.prototype.isAlive = function () {
  55524. return this._alive;
  55525. };
  55526. /**
  55527. * Gets Wether the system has been started.
  55528. * @returns True if it has been started, otherwise false.
  55529. */
  55530. ParticleSystem.prototype.isStarted = function () {
  55531. return this._started;
  55532. };
  55533. /**
  55534. * Starts the particle system and begins to emit.
  55535. */
  55536. ParticleSystem.prototype.start = function () {
  55537. this._started = true;
  55538. this._stopped = false;
  55539. this._actualFrame = 0;
  55540. if (this.subEmitters && this.subEmitters.length != 0) {
  55541. this.activeSubSystems = new Array();
  55542. }
  55543. if (this.preWarmCycles) {
  55544. for (var index = 0; index < this.preWarmCycles; index++) {
  55545. this.animate(true);
  55546. }
  55547. }
  55548. };
  55549. /**
  55550. * Stops the particle system.
  55551. * @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.
  55552. */
  55553. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55554. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55555. this._stopped = true;
  55556. if (stopSubEmitters) {
  55557. this._stopSubEmitters();
  55558. }
  55559. };
  55560. // animation sheet
  55561. /**
  55562. * Remove all active particles
  55563. */
  55564. ParticleSystem.prototype.reset = function () {
  55565. this._stockParticles = [];
  55566. this._particles = [];
  55567. };
  55568. /**
  55569. * @hidden (for internal use only)
  55570. */
  55571. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55572. var offset = index * this._vertexBufferSize;
  55573. this._vertexData[offset++] = particle.position.x;
  55574. this._vertexData[offset++] = particle.position.y;
  55575. this._vertexData[offset++] = particle.position.z;
  55576. this._vertexData[offset++] = particle.color.r;
  55577. this._vertexData[offset++] = particle.color.g;
  55578. this._vertexData[offset++] = particle.color.b;
  55579. this._vertexData[offset++] = particle.color.a;
  55580. this._vertexData[offset++] = particle.angle;
  55581. this._vertexData[offset++] = particle.scale.x * particle.size;
  55582. this._vertexData[offset++] = particle.scale.y * particle.size;
  55583. if (this._isAnimationSheetEnabled) {
  55584. this._vertexData[offset++] = particle.cellIndex;
  55585. }
  55586. if (!this._isBillboardBased) {
  55587. if (particle._initialDirection) {
  55588. this._vertexData[offset++] = particle._initialDirection.x;
  55589. this._vertexData[offset++] = particle._initialDirection.y;
  55590. this._vertexData[offset++] = particle._initialDirection.z;
  55591. }
  55592. else {
  55593. this._vertexData[offset++] = particle.direction.x;
  55594. this._vertexData[offset++] = particle.direction.y;
  55595. this._vertexData[offset++] = particle.direction.z;
  55596. }
  55597. }
  55598. if (!this._useInstancing) {
  55599. if (this._isAnimationSheetEnabled) {
  55600. if (offsetX === 0)
  55601. offsetX = this._epsilon;
  55602. else if (offsetX === 1)
  55603. offsetX = 1 - this._epsilon;
  55604. if (offsetY === 0)
  55605. offsetY = this._epsilon;
  55606. else if (offsetY === 1)
  55607. offsetY = 1 - this._epsilon;
  55608. }
  55609. this._vertexData[offset++] = offsetX;
  55610. this._vertexData[offset++] = offsetY;
  55611. }
  55612. };
  55613. ParticleSystem.prototype._stopSubEmitters = function () {
  55614. if (!this.activeSubSystems) {
  55615. return;
  55616. }
  55617. this.activeSubSystems.forEach(function (subSystem) {
  55618. subSystem.stop(true);
  55619. });
  55620. this.activeSubSystems = new Array();
  55621. };
  55622. ParticleSystem.prototype._removeFromRoot = function () {
  55623. if (!this._rootParticleSystem) {
  55624. return;
  55625. }
  55626. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55627. if (index !== -1) {
  55628. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55629. }
  55630. };
  55631. // End of sub system methods
  55632. ParticleSystem.prototype._update = function (newParticles) {
  55633. // Update current
  55634. this._alive = this._particles.length > 0;
  55635. this.updateFunction(this._particles);
  55636. // Add new ones
  55637. var worldMatrix;
  55638. if (this.emitter.position) {
  55639. var emitterMesh = this.emitter;
  55640. worldMatrix = emitterMesh.getWorldMatrix();
  55641. }
  55642. else {
  55643. var emitterPosition = this.emitter;
  55644. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55645. }
  55646. var particle;
  55647. var _loop_2 = function () {
  55648. if (this_1._particles.length === this_1._capacity) {
  55649. return "break";
  55650. }
  55651. particle = this_1._createParticle();
  55652. this_1._particles.push(particle);
  55653. // Emitter
  55654. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55655. if (this_1.startPositionFunction) {
  55656. this_1.startPositionFunction(worldMatrix, particle.position, particle);
  55657. }
  55658. else {
  55659. this_1.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55660. }
  55661. if (this_1.startDirectionFunction) {
  55662. this_1.startDirectionFunction(worldMatrix, particle.direction, particle);
  55663. }
  55664. else {
  55665. this_1.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55666. }
  55667. if (emitPower === 0) {
  55668. if (!particle._initialDirection) {
  55669. particle._initialDirection = particle.direction.clone();
  55670. }
  55671. else {
  55672. particle._initialDirection.copyFrom(particle.direction);
  55673. }
  55674. }
  55675. else {
  55676. particle._initialDirection = null;
  55677. }
  55678. particle.direction.scaleInPlace(emitPower);
  55679. // Life time
  55680. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55681. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55682. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55683. var factorGradient1 = currentGradient;
  55684. var factorGradient2 = nextGradient;
  55685. var lifeTime1 = factorGradient1.getFactor();
  55686. var lifeTime2 = factorGradient2.getFactor();
  55687. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55688. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55689. });
  55690. }
  55691. else {
  55692. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55693. }
  55694. // Size
  55695. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  55696. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  55697. }
  55698. else {
  55699. particle._currentSizeGradient = this_1._sizeGradients[0];
  55700. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  55701. particle.size = particle._currentSize1;
  55702. if (this_1._sizeGradients.length > 1) {
  55703. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  55704. }
  55705. else {
  55706. particle._currentSize2 = particle._currentSize1;
  55707. }
  55708. }
  55709. // Size and scale
  55710. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  55711. // Angle
  55712. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  55713. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  55714. }
  55715. else {
  55716. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  55717. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  55718. particle._currentAngularSpeed1 = particle.angularSpeed;
  55719. if (this_1._angularSpeedGradients.length > 1) {
  55720. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  55721. }
  55722. else {
  55723. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  55724. }
  55725. }
  55726. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  55727. // Velocity
  55728. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  55729. particle._currentVelocityGradient = this_1._velocityGradients[0];
  55730. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  55731. if (this_1._velocityGradients.length > 1) {
  55732. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  55733. }
  55734. else {
  55735. particle._currentVelocity2 = particle._currentVelocity1;
  55736. }
  55737. }
  55738. // Color
  55739. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  55740. step = BABYLON.Scalar.RandomRange(0, 1.0);
  55741. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  55742. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  55743. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55744. }
  55745. else {
  55746. particle._currentColorGradient = this_1._colorGradients[0];
  55747. particle._currentColorGradient.getColorToRef(particle.color);
  55748. particle._currentColor1.copyFrom(particle.color);
  55749. if (this_1._colorGradients.length > 1) {
  55750. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  55751. }
  55752. else {
  55753. particle._currentColor2.copyFrom(particle.color);
  55754. }
  55755. }
  55756. // Sheet
  55757. if (this_1._isAnimationSheetEnabled) {
  55758. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  55759. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  55760. }
  55761. };
  55762. var this_1 = this, step;
  55763. for (var index = 0; index < newParticles; index++) {
  55764. var state_1 = _loop_2();
  55765. if (state_1 === "break")
  55766. break;
  55767. }
  55768. };
  55769. /** @hidden */
  55770. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55771. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55772. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55773. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55774. if (isAnimationSheetEnabled) {
  55775. attributeNamesOrOptions.push("cellIndex");
  55776. }
  55777. if (!isBillboardBased) {
  55778. attributeNamesOrOptions.push("direction");
  55779. }
  55780. return attributeNamesOrOptions;
  55781. };
  55782. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  55783. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55784. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  55785. if (isAnimationSheetEnabled) {
  55786. effectCreationOption.push("particlesInfos");
  55787. }
  55788. return effectCreationOption;
  55789. };
  55790. ParticleSystem.prototype._getEffect = function () {
  55791. if (this._customEffect) {
  55792. return this._customEffect;
  55793. }
  55794. ;
  55795. var defines = [];
  55796. if (this._scene.clipPlane) {
  55797. defines.push("#define CLIPPLANE");
  55798. }
  55799. if (this._isAnimationSheetEnabled) {
  55800. defines.push("#define ANIMATESHEET");
  55801. }
  55802. if (this._isBillboardBased) {
  55803. defines.push("#define BILLBOARD");
  55804. switch (this.billboardMode) {
  55805. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  55806. defines.push("#define BILLBOARDY");
  55807. break;
  55808. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  55809. default:
  55810. break;
  55811. }
  55812. }
  55813. // Effect
  55814. var join = defines.join("\n");
  55815. if (this._cachedDefines !== join) {
  55816. this._cachedDefines = join;
  55817. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  55818. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  55819. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55820. }
  55821. return this._effect;
  55822. };
  55823. /**
  55824. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55825. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55826. */
  55827. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55828. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55829. if (!this._started)
  55830. return;
  55831. if (!preWarmOnly) {
  55832. var effect = this._getEffect();
  55833. // Check
  55834. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55835. return;
  55836. if (this._currentRenderId === this._scene.getRenderId()) {
  55837. return;
  55838. }
  55839. this._currentRenderId = this._scene.getRenderId();
  55840. }
  55841. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55842. // determine the number of particles we need to create
  55843. var newParticles;
  55844. if (this.manualEmitCount > -1) {
  55845. newParticles = this.manualEmitCount;
  55846. this._newPartsExcess = 0;
  55847. this.manualEmitCount = 0;
  55848. }
  55849. else {
  55850. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55851. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55852. }
  55853. if (this._newPartsExcess > 1.0) {
  55854. newParticles += this._newPartsExcess >> 0;
  55855. this._newPartsExcess -= this._newPartsExcess >> 0;
  55856. }
  55857. this._alive = false;
  55858. if (!this._stopped) {
  55859. this._actualFrame += this._scaledUpdateSpeed;
  55860. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55861. this.stop();
  55862. }
  55863. else {
  55864. newParticles = 0;
  55865. }
  55866. this._update(newParticles);
  55867. // Stopped?
  55868. if (this._stopped) {
  55869. if (!this._alive) {
  55870. this._started = false;
  55871. if (this.onAnimationEnd) {
  55872. this.onAnimationEnd();
  55873. }
  55874. if (this.disposeOnStop) {
  55875. this._scene._toBeDisposed.push(this);
  55876. }
  55877. }
  55878. }
  55879. if (!preWarmOnly) {
  55880. // Update VBO
  55881. var offset = 0;
  55882. for (var index = 0; index < this._particles.length; index++) {
  55883. var particle = this._particles[index];
  55884. this._appendParticleVertices(offset, particle);
  55885. offset += this._useInstancing ? 1 : 4;
  55886. }
  55887. if (this._vertexBuffer) {
  55888. this._vertexBuffer.update(this._vertexData);
  55889. }
  55890. }
  55891. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55892. this.stop();
  55893. }
  55894. };
  55895. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  55896. this._appendParticleVertex(offset++, particle, 0, 0);
  55897. if (!this._useInstancing) {
  55898. this._appendParticleVertex(offset++, particle, 1, 0);
  55899. this._appendParticleVertex(offset++, particle, 1, 1);
  55900. this._appendParticleVertex(offset++, particle, 0, 1);
  55901. }
  55902. };
  55903. /**
  55904. * Rebuilds the particle system.
  55905. */
  55906. ParticleSystem.prototype.rebuild = function () {
  55907. this._createIndexBuffer();
  55908. if (this._vertexBuffer) {
  55909. this._vertexBuffer._rebuild();
  55910. }
  55911. };
  55912. /**
  55913. * Is this system ready to be used/rendered
  55914. * @return true if the system is ready
  55915. */
  55916. ParticleSystem.prototype.isReady = function () {
  55917. var effect = this._getEffect();
  55918. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55919. return false;
  55920. }
  55921. return true;
  55922. };
  55923. /**
  55924. * Renders the particle system in its current state.
  55925. * @returns the current number of particles
  55926. */
  55927. ParticleSystem.prototype.render = function () {
  55928. var effect = this._getEffect();
  55929. // Check
  55930. if (!this.isReady() || !this._particles.length) {
  55931. return 0;
  55932. }
  55933. var engine = this._scene.getEngine();
  55934. // Render
  55935. engine.enableEffect(effect);
  55936. engine.setState(false);
  55937. var viewMatrix = this._scene.getViewMatrix();
  55938. effect.setTexture("diffuseSampler", this.particleTexture);
  55939. effect.setMatrix("view", viewMatrix);
  55940. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55941. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55942. var baseSize = this.particleTexture.getBaseSize();
  55943. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55944. }
  55945. effect.setVector2("translationPivot", this.translationPivot);
  55946. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55947. if (this._isBillboardBased) {
  55948. var camera = this._scene.activeCamera;
  55949. effect.setVector3("eyePosition", camera.globalPosition);
  55950. }
  55951. if (this._scene.clipPlane) {
  55952. var clipPlane = this._scene.clipPlane;
  55953. var invView = viewMatrix.clone();
  55954. invView.invert();
  55955. effect.setMatrix("invView", invView);
  55956. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55957. }
  55958. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55959. // Draw order
  55960. switch (this.blendMode) {
  55961. case ParticleSystem.BLENDMODE_ADD:
  55962. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  55963. break;
  55964. case ParticleSystem.BLENDMODE_ONEONE:
  55965. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55966. break;
  55967. case ParticleSystem.BLENDMODE_STANDARD:
  55968. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55969. break;
  55970. }
  55971. if (this.forceDepthWrite) {
  55972. engine.setDepthWrite(true);
  55973. }
  55974. if (this._useInstancing) {
  55975. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  55976. engine.unbindInstanceAttributes();
  55977. }
  55978. else {
  55979. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55980. }
  55981. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55982. return this._particles.length;
  55983. };
  55984. /**
  55985. * Disposes the particle system and free the associated resources
  55986. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55987. */
  55988. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55989. if (disposeTexture === void 0) { disposeTexture = true; }
  55990. if (this._vertexBuffer) {
  55991. this._vertexBuffer.dispose();
  55992. this._vertexBuffer = null;
  55993. }
  55994. if (this._spriteBuffer) {
  55995. this._spriteBuffer.dispose();
  55996. this._spriteBuffer = null;
  55997. }
  55998. if (this._indexBuffer) {
  55999. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56000. this._indexBuffer = null;
  56001. }
  56002. if (disposeTexture && this.particleTexture) {
  56003. this.particleTexture.dispose();
  56004. this.particleTexture = null;
  56005. }
  56006. this._removeFromRoot();
  56007. // Remove from scene
  56008. var index = this._scene.particleSystems.indexOf(this);
  56009. if (index > -1) {
  56010. this._scene.particleSystems.splice(index, 1);
  56011. }
  56012. // Callback
  56013. this.onDisposeObservable.notifyObservers(this);
  56014. this.onDisposeObservable.clear();
  56015. };
  56016. /**
  56017. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56018. * @param radius The radius of the sphere to emit from
  56019. * @returns the emitter
  56020. */
  56021. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56022. if (radius === void 0) { radius = 1; }
  56023. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56024. this.particleEmitterType = particleEmitter;
  56025. return particleEmitter;
  56026. };
  56027. /**
  56028. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56029. * @param radius The radius of the sphere to emit from
  56030. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56031. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56032. * @returns the emitter
  56033. */
  56034. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56035. if (radius === void 0) { radius = 1; }
  56036. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56037. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56038. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56039. this.particleEmitterType = particleEmitter;
  56040. return particleEmitter;
  56041. };
  56042. /**
  56043. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56044. * @param radius The radius of the cone to emit from
  56045. * @param angle The base angle of the cone
  56046. * @returns the emitter
  56047. */
  56048. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56049. if (radius === void 0) { radius = 1; }
  56050. if (angle === void 0) { angle = Math.PI / 4; }
  56051. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56052. this.particleEmitterType = particleEmitter;
  56053. return particleEmitter;
  56054. };
  56055. // 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.
  56056. /**
  56057. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56058. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56059. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56060. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56061. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56062. * @returns the emitter
  56063. */
  56064. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56065. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56066. this.particleEmitterType = particleEmitter;
  56067. this.direction1 = direction1;
  56068. this.direction2 = direction2;
  56069. this.minEmitBox = minEmitBox;
  56070. this.maxEmitBox = maxEmitBox;
  56071. return particleEmitter;
  56072. };
  56073. // Clone
  56074. /**
  56075. * Clones the particle system.
  56076. * @param name The name of the cloned object
  56077. * @param newEmitter The new emitter to use
  56078. * @returns the cloned particle system
  56079. */
  56080. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56081. var custom = null;
  56082. var program = null;
  56083. if (this.customShader != null) {
  56084. program = this.customShader;
  56085. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56086. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56087. }
  56088. else if (this._customEffect) {
  56089. custom = this._customEffect;
  56090. }
  56091. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56092. result.customShader = program;
  56093. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56094. if (newEmitter === undefined) {
  56095. newEmitter = this.emitter;
  56096. }
  56097. result.emitter = newEmitter;
  56098. if (this.particleTexture) {
  56099. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56100. }
  56101. if (!this.preventAutoStart) {
  56102. result.start();
  56103. }
  56104. return result;
  56105. };
  56106. /**
  56107. * Serializes the particle system to a JSON object.
  56108. * @returns the JSON object
  56109. */
  56110. ParticleSystem.prototype.serialize = function () {
  56111. var serializationObject = {};
  56112. ParticleSystem._Serialize(serializationObject, this);
  56113. serializationObject.textureMask = this.textureMask.asArray();
  56114. serializationObject.customShader = this.customShader;
  56115. serializationObject.preventAutoStart = this.preventAutoStart;
  56116. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56117. return serializationObject;
  56118. };
  56119. /** @hidden */
  56120. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56121. serializationObject.name = particleSystem.name;
  56122. serializationObject.id = particleSystem.id;
  56123. serializationObject.capacity = particleSystem.getCapacity();
  56124. // Emitter
  56125. if (particleSystem.emitter.position) {
  56126. var emitterMesh = particleSystem.emitter;
  56127. serializationObject.emitterId = emitterMesh.id;
  56128. }
  56129. else {
  56130. var emitterPosition = particleSystem.emitter;
  56131. serializationObject.emitter = emitterPosition.asArray();
  56132. }
  56133. // Emitter
  56134. if (particleSystem.particleEmitterType) {
  56135. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56136. }
  56137. if (particleSystem.particleTexture) {
  56138. serializationObject.textureName = particleSystem.particleTexture.name;
  56139. }
  56140. // Animations
  56141. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56142. // Particle system
  56143. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  56144. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  56145. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56146. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56147. serializationObject.minSize = particleSystem.minSize;
  56148. serializationObject.maxSize = particleSystem.maxSize;
  56149. serializationObject.minScaleX = particleSystem.minScaleX;
  56150. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56151. serializationObject.minScaleY = particleSystem.minScaleY;
  56152. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56153. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56154. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56155. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56156. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56157. serializationObject.emitRate = particleSystem.emitRate;
  56158. serializationObject.gravity = particleSystem.gravity.asArray();
  56159. serializationObject.color1 = particleSystem.color1.asArray();
  56160. serializationObject.color2 = particleSystem.color2.asArray();
  56161. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56162. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56163. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56164. serializationObject.blendMode = particleSystem.blendMode;
  56165. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56166. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56167. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56168. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56169. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56170. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56171. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56172. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56173. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56174. var colorGradients = particleSystem.getColorGradients();
  56175. if (colorGradients) {
  56176. serializationObject.colorGradients = [];
  56177. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56178. var colorGradient = colorGradients_1[_i];
  56179. var serializedGradient = {
  56180. gradient: colorGradient.gradient,
  56181. color1: colorGradient.color1.asArray()
  56182. };
  56183. if (colorGradient.color2) {
  56184. serializedGradient.color2 = colorGradient.color2.asArray();
  56185. }
  56186. serializationObject.colorGradients.push(serializedGradient);
  56187. }
  56188. }
  56189. var sizeGradients = particleSystem.getSizeGradients();
  56190. if (sizeGradients) {
  56191. serializationObject.sizeGradients = [];
  56192. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56193. var sizeGradient = sizeGradients_1[_a];
  56194. var serializedGradient = {
  56195. gradient: sizeGradient.gradient,
  56196. factor1: sizeGradient.factor1
  56197. };
  56198. if (sizeGradient.factor2 !== undefined) {
  56199. serializedGradient.factor2 = sizeGradient.factor2;
  56200. }
  56201. serializationObject.sizeGradients.push(serializedGradient);
  56202. }
  56203. }
  56204. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  56205. if (angularSpeedGradients) {
  56206. serializationObject.angularSpeedGradients = [];
  56207. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  56208. var angularSpeedGradient = angularSpeedGradients_1[_b];
  56209. var serializedGradient = {
  56210. gradient: angularSpeedGradient.gradient,
  56211. factor1: angularSpeedGradient.factor1
  56212. };
  56213. if (angularSpeedGradient.factor2 !== undefined) {
  56214. serializedGradient.factor2 = angularSpeedGradient.factor2;
  56215. }
  56216. serializationObject.angularSpeedGradients.push(serializedGradient);
  56217. }
  56218. }
  56219. var velocityGradients = particleSystem.getVelocityGradients();
  56220. if (velocityGradients) {
  56221. serializationObject.velocityGradients = [];
  56222. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  56223. var velocityGradient = velocityGradients_1[_c];
  56224. var serializedGradient = {
  56225. gradient: velocityGradient.gradient,
  56226. factor1: velocityGradient.factor1
  56227. };
  56228. if (velocityGradient.factor2 !== undefined) {
  56229. serializedGradient.factor2 = velocityGradient.factor2;
  56230. }
  56231. serializationObject.velocityGradients.push(serializedGradient);
  56232. }
  56233. }
  56234. };
  56235. /** @hidden */
  56236. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56237. // Texture
  56238. if (parsedParticleSystem.textureName) {
  56239. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56240. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56241. }
  56242. // Emitter
  56243. if (parsedParticleSystem.emitterId === undefined) {
  56244. particleSystem.emitter = BABYLON.Vector3.Zero();
  56245. }
  56246. else if (parsedParticleSystem.emitterId) {
  56247. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56248. }
  56249. else {
  56250. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56251. }
  56252. // Misc.
  56253. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56254. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56255. }
  56256. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56257. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56258. }
  56259. // Animations
  56260. if (parsedParticleSystem.animations) {
  56261. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56262. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56263. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56264. }
  56265. }
  56266. if (parsedParticleSystem.autoAnimate) {
  56267. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56268. }
  56269. // Particle system
  56270. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56271. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56272. particleSystem.minSize = parsedParticleSystem.minSize;
  56273. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56274. if (parsedParticleSystem.minScaleX) {
  56275. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56276. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56277. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56278. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56279. }
  56280. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56281. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56282. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56283. }
  56284. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56285. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56286. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56287. }
  56288. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56289. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56290. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56291. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56292. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56293. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56294. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56295. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56296. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56297. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56298. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56299. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56300. if (parsedParticleSystem.colorGradients) {
  56301. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56302. var colorGradient = _a[_i];
  56303. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56304. }
  56305. }
  56306. if (parsedParticleSystem.sizeGradients) {
  56307. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56308. var sizeGradient = _c[_b];
  56309. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56310. }
  56311. }
  56312. if (parsedParticleSystem.angularSpeedGradients) {
  56313. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  56314. var angularSpeedGradient = _e[_d];
  56315. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  56316. }
  56317. }
  56318. if (parsedParticleSystem.velocityGradients) {
  56319. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  56320. var velocityGradient = _g[_f];
  56321. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  56322. }
  56323. }
  56324. // Emitter
  56325. var emitterType;
  56326. if (parsedParticleSystem.particleEmitterType) {
  56327. switch (parsedParticleSystem.particleEmitterType.type) {
  56328. case "SphereParticleEmitter":
  56329. emitterType = new BABYLON.SphereParticleEmitter();
  56330. break;
  56331. case "SphereDirectedParticleEmitter":
  56332. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56333. break;
  56334. case "ConeEmitter":
  56335. case "ConeParticleEmitter":
  56336. emitterType = new BABYLON.ConeParticleEmitter();
  56337. break;
  56338. case "BoxEmitter":
  56339. case "BoxParticleEmitter":
  56340. default:
  56341. emitterType = new BABYLON.BoxParticleEmitter();
  56342. break;
  56343. }
  56344. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56345. }
  56346. else {
  56347. emitterType = new BABYLON.BoxParticleEmitter();
  56348. emitterType.parse(parsedParticleSystem);
  56349. }
  56350. particleSystem.particleEmitterType = emitterType;
  56351. // Animation sheet
  56352. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56353. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56354. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56355. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56356. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56357. };
  56358. /**
  56359. * Parses a JSON object to create a particle system.
  56360. * @param parsedParticleSystem The JSON object to parse
  56361. * @param scene The scene to create the particle system in
  56362. * @param rootUrl The root url to use to load external dependencies like texture
  56363. * @returns the Parsed particle system
  56364. */
  56365. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56366. var name = parsedParticleSystem.name;
  56367. var custom = null;
  56368. var program = null;
  56369. if (parsedParticleSystem.customShader) {
  56370. program = parsedParticleSystem.customShader;
  56371. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56372. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56373. }
  56374. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56375. particleSystem.customShader = program;
  56376. if (parsedParticleSystem.id) {
  56377. particleSystem.id = parsedParticleSystem.id;
  56378. }
  56379. // Auto start
  56380. if (parsedParticleSystem.preventAutoStart) {
  56381. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56382. }
  56383. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56384. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56385. if (!particleSystem.preventAutoStart) {
  56386. particleSystem.start();
  56387. }
  56388. return particleSystem;
  56389. };
  56390. /**
  56391. * Source color is added to the destination color without alpha affecting the result.
  56392. */
  56393. ParticleSystem.BLENDMODE_ONEONE = 0;
  56394. /**
  56395. * Blend current color and particle color using particle’s alpha.
  56396. */
  56397. ParticleSystem.BLENDMODE_STANDARD = 1;
  56398. /**
  56399. * Add current color and particle color multiplied by particle’s alpha.
  56400. */
  56401. ParticleSystem.BLENDMODE_ADD = 2;
  56402. return ParticleSystem;
  56403. }());
  56404. BABYLON.ParticleSystem = ParticleSystem;
  56405. })(BABYLON || (BABYLON = {}));
  56406. //# sourceMappingURL=babylon.particleSystem.js.map
  56407. var BABYLON;
  56408. (function (BABYLON) {
  56409. /**
  56410. * Particle emitter emitting particles from the inside of a box.
  56411. * It emits the particles randomly between 2 given directions.
  56412. */
  56413. var BoxParticleEmitter = /** @class */ (function () {
  56414. /**
  56415. * Creates a new instance BoxParticleEmitter
  56416. */
  56417. function BoxParticleEmitter() {
  56418. /**
  56419. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56420. */
  56421. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56422. /**
  56423. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56424. */
  56425. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56426. /**
  56427. * 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.
  56428. */
  56429. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56430. /**
  56431. * 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.
  56432. */
  56433. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56434. }
  56435. /**
  56436. * Called by the particle System when the direction is computed for the created particle.
  56437. * @param worldMatrix is the world matrix of the particle system
  56438. * @param directionToUpdate is the direction vector to update with the result
  56439. * @param particle is the particle we are computed the direction for
  56440. */
  56441. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56442. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56443. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56444. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56445. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56446. };
  56447. /**
  56448. * Called by the particle System when the position is computed for the created particle.
  56449. * @param worldMatrix is the world matrix of the particle system
  56450. * @param positionToUpdate is the position vector to update with the result
  56451. * @param particle is the particle we are computed the position for
  56452. */
  56453. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56454. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56455. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56456. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56457. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56458. };
  56459. /**
  56460. * Clones the current emitter and returns a copy of it
  56461. * @returns the new emitter
  56462. */
  56463. BoxParticleEmitter.prototype.clone = function () {
  56464. var newOne = new BoxParticleEmitter();
  56465. BABYLON.Tools.DeepCopy(this, newOne);
  56466. return newOne;
  56467. };
  56468. /**
  56469. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56470. * @param effect defines the update shader
  56471. */
  56472. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56473. effect.setVector3("direction1", this.direction1);
  56474. effect.setVector3("direction2", this.direction2);
  56475. effect.setVector3("minEmitBox", this.minEmitBox);
  56476. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56477. };
  56478. /**
  56479. * Returns a string to use to update the GPU particles update shader
  56480. * @returns a string containng the defines string
  56481. */
  56482. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56483. return "#define BOXEMITTER";
  56484. };
  56485. /**
  56486. * Returns the string "BoxParticleEmitter"
  56487. * @returns a string containing the class name
  56488. */
  56489. BoxParticleEmitter.prototype.getClassName = function () {
  56490. return "BoxParticleEmitter";
  56491. };
  56492. /**
  56493. * Serializes the particle system to a JSON object.
  56494. * @returns the JSON object
  56495. */
  56496. BoxParticleEmitter.prototype.serialize = function () {
  56497. var serializationObject = {};
  56498. serializationObject.type = this.getClassName();
  56499. serializationObject.direction1 = this.direction1.asArray();
  56500. serializationObject.direction2 = this.direction2.asArray();
  56501. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56502. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56503. return serializationObject;
  56504. };
  56505. /**
  56506. * Parse properties from a JSON object
  56507. * @param serializationObject defines the JSON object
  56508. */
  56509. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56510. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56511. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56512. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56513. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56514. };
  56515. return BoxParticleEmitter;
  56516. }());
  56517. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56518. })(BABYLON || (BABYLON = {}));
  56519. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56520. var BABYLON;
  56521. (function (BABYLON) {
  56522. /**
  56523. * Particle emitter emitting particles from the inside of a cone.
  56524. * It emits the particles alongside the cone volume from the base to the particle.
  56525. * The emission direction might be randomized.
  56526. */
  56527. var ConeParticleEmitter = /** @class */ (function () {
  56528. /**
  56529. * Creates a new instance ConeParticleEmitter
  56530. * @param radius the radius of the emission cone (1 by default)
  56531. * @param angles the cone base angle (PI by default)
  56532. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56533. */
  56534. function ConeParticleEmitter(radius, angle,
  56535. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56536. directionRandomizer) {
  56537. if (radius === void 0) { radius = 1; }
  56538. if (angle === void 0) { angle = Math.PI; }
  56539. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56540. this.directionRandomizer = directionRandomizer;
  56541. /**
  56542. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56543. */
  56544. this.radiusRange = 1;
  56545. /**
  56546. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  56547. */
  56548. this.heightRange = 1;
  56549. this.angle = angle;
  56550. this.radius = radius;
  56551. }
  56552. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56553. /**
  56554. * Gets or sets the radius of the emission cone
  56555. */
  56556. get: function () {
  56557. return this._radius;
  56558. },
  56559. set: function (value) {
  56560. this._radius = value;
  56561. this._buildHeight();
  56562. },
  56563. enumerable: true,
  56564. configurable: true
  56565. });
  56566. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56567. /**
  56568. * Gets or sets the angle of the emission cone
  56569. */
  56570. get: function () {
  56571. return this._angle;
  56572. },
  56573. set: function (value) {
  56574. this._angle = value;
  56575. this._buildHeight();
  56576. },
  56577. enumerable: true,
  56578. configurable: true
  56579. });
  56580. ConeParticleEmitter.prototype._buildHeight = function () {
  56581. if (this._angle !== 0) {
  56582. this._height = this._radius / Math.tan(this._angle / 2);
  56583. }
  56584. else {
  56585. this._height = 1;
  56586. }
  56587. };
  56588. /**
  56589. * Called by the particle System when the direction is computed for the created particle.
  56590. * @param worldMatrix is the world matrix of the particle system
  56591. * @param directionToUpdate is the direction vector to update with the result
  56592. * @param particle is the particle we are computed the direction for
  56593. */
  56594. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56595. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  56596. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56597. }
  56598. else {
  56599. // measure the direction Vector from the emitter to the particle.
  56600. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56601. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56602. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56603. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56604. direction.x += randX;
  56605. direction.y += randY;
  56606. direction.z += randZ;
  56607. direction.normalize();
  56608. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56609. }
  56610. };
  56611. /**
  56612. * Called by the particle System when the position is computed for the created particle.
  56613. * @param worldMatrix is the world matrix of the particle system
  56614. * @param positionToUpdate is the position vector to update with the result
  56615. * @param particle is the particle we are computed the position for
  56616. */
  56617. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56618. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56619. var h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  56620. // Better distribution in a cone at normal angles.
  56621. h = 1 - h * h;
  56622. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  56623. radius = radius * h;
  56624. var randX = radius * Math.sin(s);
  56625. var randZ = radius * Math.cos(s);
  56626. var randY = h * this._height;
  56627. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56628. };
  56629. /**
  56630. * Clones the current emitter and returns a copy of it
  56631. * @returns the new emitter
  56632. */
  56633. ConeParticleEmitter.prototype.clone = function () {
  56634. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56635. BABYLON.Tools.DeepCopy(this, newOne);
  56636. return newOne;
  56637. };
  56638. /**
  56639. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56640. * @param effect defines the update shader
  56641. */
  56642. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56643. effect.setFloat2("radius", this._radius, this.radiusRange);
  56644. effect.setFloat("coneAngle", this._angle);
  56645. effect.setFloat2("height", this._height, this.heightRange);
  56646. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56647. };
  56648. /**
  56649. * Returns a string to use to update the GPU particles update shader
  56650. * @returns a string containng the defines string
  56651. */
  56652. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56653. return "#define CONEEMITTER";
  56654. };
  56655. /**
  56656. * Returns the string "ConeParticleEmitter"
  56657. * @returns a string containing the class name
  56658. */
  56659. ConeParticleEmitter.prototype.getClassName = function () {
  56660. return "ConeParticleEmitter";
  56661. };
  56662. /**
  56663. * Serializes the particle system to a JSON object.
  56664. * @returns the JSON object
  56665. */
  56666. ConeParticleEmitter.prototype.serialize = function () {
  56667. var serializationObject = {};
  56668. serializationObject.type = this.getClassName();
  56669. serializationObject.radius = this._radius;
  56670. serializationObject.angle = this._angle;
  56671. serializationObject.directionRandomizer = this.directionRandomizer;
  56672. return serializationObject;
  56673. };
  56674. /**
  56675. * Parse properties from a JSON object
  56676. * @param serializationObject defines the JSON object
  56677. */
  56678. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56679. this.radius = serializationObject.radius;
  56680. this.angle = serializationObject.angle;
  56681. this.directionRandomizer = serializationObject.directionRandomizer;
  56682. };
  56683. return ConeParticleEmitter;
  56684. }());
  56685. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56686. })(BABYLON || (BABYLON = {}));
  56687. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56688. var BABYLON;
  56689. (function (BABYLON) {
  56690. /**
  56691. * Particle emitter emitting particles from the inside of a sphere.
  56692. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56693. */
  56694. var SphereParticleEmitter = /** @class */ (function () {
  56695. /**
  56696. * Creates a new instance SphereParticleEmitter
  56697. * @param radius the radius of the emission sphere (1 by default)
  56698. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56699. */
  56700. function SphereParticleEmitter(
  56701. /**
  56702. * The radius of the emission sphere.
  56703. */
  56704. radius,
  56705. /**
  56706. * How much to randomize the particle direction [0-1].
  56707. */
  56708. directionRandomizer) {
  56709. if (radius === void 0) { radius = 1; }
  56710. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56711. this.radius = radius;
  56712. this.directionRandomizer = directionRandomizer;
  56713. /**
  56714. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56715. */
  56716. this.radiusRange = 1;
  56717. }
  56718. /**
  56719. * Called by the particle System when the direction is computed for the created particle.
  56720. * @param worldMatrix is the world matrix of the particle system
  56721. * @param directionToUpdate is the direction vector to update with the result
  56722. * @param particle is the particle we are computed the direction for
  56723. */
  56724. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56725. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56726. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56727. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56728. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56729. direction.x += randX;
  56730. direction.y += randY;
  56731. direction.z += randZ;
  56732. direction.normalize();
  56733. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56734. };
  56735. /**
  56736. * Called by the particle System when the position is computed for the created particle.
  56737. * @param worldMatrix is the world matrix of the particle system
  56738. * @param positionToUpdate is the position vector to update with the result
  56739. * @param particle is the particle we are computed the position for
  56740. */
  56741. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56742. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56743. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56744. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56745. var theta = Math.acos(2 * v - 1);
  56746. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56747. var randY = randRadius * Math.cos(theta);
  56748. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56749. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56750. };
  56751. /**
  56752. * Clones the current emitter and returns a copy of it
  56753. * @returns the new emitter
  56754. */
  56755. SphereParticleEmitter.prototype.clone = function () {
  56756. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56757. BABYLON.Tools.DeepCopy(this, newOne);
  56758. return newOne;
  56759. };
  56760. /**
  56761. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56762. * @param effect defines the update shader
  56763. */
  56764. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56765. effect.setFloat("radius", this.radius);
  56766. effect.setFloat("radiusRange", this.radiusRange);
  56767. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56768. };
  56769. /**
  56770. * Returns a string to use to update the GPU particles update shader
  56771. * @returns a string containng the defines string
  56772. */
  56773. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56774. return "#define SPHEREEMITTER";
  56775. };
  56776. /**
  56777. * Returns the string "SphereParticleEmitter"
  56778. * @returns a string containing the class name
  56779. */
  56780. SphereParticleEmitter.prototype.getClassName = function () {
  56781. return "SphereParticleEmitter";
  56782. };
  56783. /**
  56784. * Serializes the particle system to a JSON object.
  56785. * @returns the JSON object
  56786. */
  56787. SphereParticleEmitter.prototype.serialize = function () {
  56788. var serializationObject = {};
  56789. serializationObject.type = this.getClassName();
  56790. serializationObject.radius = this.radius;
  56791. serializationObject.radiusRange = this.radiusRange;
  56792. serializationObject.directionRandomizer = this.directionRandomizer;
  56793. return serializationObject;
  56794. };
  56795. /**
  56796. * Parse properties from a JSON object
  56797. * @param serializationObject defines the JSON object
  56798. */
  56799. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56800. this.radius = serializationObject.radius;
  56801. this.radiusRange = serializationObject.radiusRange;
  56802. this.directionRandomizer = serializationObject.directionRandomizer;
  56803. };
  56804. return SphereParticleEmitter;
  56805. }());
  56806. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56807. /**
  56808. * Particle emitter emitting particles from the inside of a sphere.
  56809. * It emits the particles randomly between two vectors.
  56810. */
  56811. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56812. __extends(SphereDirectedParticleEmitter, _super);
  56813. /**
  56814. * Creates a new instance SphereDirectedParticleEmitter
  56815. * @param radius the radius of the emission sphere (1 by default)
  56816. * @param direction1 the min limit of the emission direction (up vector by default)
  56817. * @param direction2 the max limit of the emission direction (up vector by default)
  56818. */
  56819. function SphereDirectedParticleEmitter(radius,
  56820. /**
  56821. * The min limit of the emission direction.
  56822. */
  56823. direction1,
  56824. /**
  56825. * The max limit of the emission direction.
  56826. */
  56827. direction2) {
  56828. if (radius === void 0) { radius = 1; }
  56829. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56830. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56831. var _this = _super.call(this, radius) || this;
  56832. _this.direction1 = direction1;
  56833. _this.direction2 = direction2;
  56834. return _this;
  56835. }
  56836. /**
  56837. * Called by the particle System when the direction is computed for the created particle.
  56838. * @param worldMatrix is the world matrix of the particle system
  56839. * @param directionToUpdate is the direction vector to update with the result
  56840. * @param particle is the particle we are computed the direction for
  56841. */
  56842. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56843. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56844. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56845. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56846. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56847. };
  56848. /**
  56849. * Clones the current emitter and returns a copy of it
  56850. * @returns the new emitter
  56851. */
  56852. SphereDirectedParticleEmitter.prototype.clone = function () {
  56853. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56854. BABYLON.Tools.DeepCopy(this, newOne);
  56855. return newOne;
  56856. };
  56857. /**
  56858. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56859. * @param effect defines the update shader
  56860. */
  56861. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56862. effect.setFloat("radius", this.radius);
  56863. effect.setFloat("radiusRange", this.radiusRange);
  56864. effect.setVector3("direction1", this.direction1);
  56865. effect.setVector3("direction2", this.direction2);
  56866. };
  56867. /**
  56868. * Returns a string to use to update the GPU particles update shader
  56869. * @returns a string containng the defines string
  56870. */
  56871. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56872. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56873. };
  56874. /**
  56875. * Returns the string "SphereDirectedParticleEmitter"
  56876. * @returns a string containing the class name
  56877. */
  56878. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56879. return "SphereDirectedParticleEmitter";
  56880. };
  56881. /**
  56882. * Serializes the particle system to a JSON object.
  56883. * @returns the JSON object
  56884. */
  56885. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56886. var serializationObject = _super.prototype.serialize.call(this);
  56887. serializationObject.direction1 = this.direction1.asArray();
  56888. serializationObject.direction2 = this.direction2.asArray();
  56889. return serializationObject;
  56890. };
  56891. /**
  56892. * Parse properties from a JSON object
  56893. * @param serializationObject defines the JSON object
  56894. */
  56895. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56896. _super.prototype.parse.call(this, serializationObject);
  56897. this.direction1.copyFrom(serializationObject.direction1);
  56898. this.direction2.copyFrom(serializationObject.direction2);
  56899. };
  56900. return SphereDirectedParticleEmitter;
  56901. }(SphereParticleEmitter));
  56902. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56903. })(BABYLON || (BABYLON = {}));
  56904. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56905. var BABYLON;
  56906. (function (BABYLON) {
  56907. // Adds the parsers to the scene parsers.
  56908. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  56909. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  56910. if (!individualParser) {
  56911. return;
  56912. }
  56913. // Particles Systems
  56914. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  56915. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  56916. var parsedParticleSystem = parsedData.particleSystems[index];
  56917. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  56918. }
  56919. }
  56920. });
  56921. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  56922. if (parsedParticleSystem.activeParticleCount) {
  56923. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  56924. return ps;
  56925. }
  56926. else {
  56927. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  56928. return ps;
  56929. }
  56930. });
  56931. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  56932. if (uniformsNames === void 0) { uniformsNames = []; }
  56933. if (samplers === void 0) { samplers = []; }
  56934. if (defines === void 0) { defines = ""; }
  56935. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  56936. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  56937. if (defines.indexOf(" BILLBOARD") === -1) {
  56938. defines += "\n#define BILLBOARD\n";
  56939. }
  56940. if (samplers.indexOf("diffuseSampler") === -1) {
  56941. samplers.push("diffuseSampler");
  56942. }
  56943. return this.createEffect({
  56944. vertex: "particles",
  56945. fragmentElement: fragmentName
  56946. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  56947. };
  56948. })(BABYLON || (BABYLON = {}));
  56949. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  56950. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56951. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56952. s = arguments[i];
  56953. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56954. t[p] = s[p];
  56955. }
  56956. return t;
  56957. };
  56958. var BABYLON;
  56959. (function (BABYLON) {
  56960. /**
  56961. * This represents a GPU particle system in Babylon
  56962. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56963. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56964. */
  56965. var GPUParticleSystem = /** @class */ (function () {
  56966. /**
  56967. * Instantiates a GPU particle system.
  56968. * 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.
  56969. * @param name The name of the particle system
  56970. * @param options The options used to create the system
  56971. * @param scene The scene the particle system belongs to
  56972. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56973. */
  56974. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  56975. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56976. /**
  56977. * The emitter represents the Mesh or position we are attaching the particle system to.
  56978. */
  56979. this.emitter = null;
  56980. /**
  56981. * The rendering group used by the Particle system to chose when to render.
  56982. */
  56983. this.renderingGroupId = 0;
  56984. /**
  56985. * The layer mask we are rendering the particles through.
  56986. */
  56987. this.layerMask = 0x0FFFFFFF;
  56988. this._accumulatedCount = 0;
  56989. this._targetIndex = 0;
  56990. this._currentRenderId = -1;
  56991. this._started = false;
  56992. this._stopped = false;
  56993. this._timeDelta = 0;
  56994. this._attributesStrideSize = 21;
  56995. this._actualFrame = 0;
  56996. this._rawTextureWidth = 256;
  56997. /**
  56998. * List of animations used by the particle system.
  56999. */
  57000. this.animations = [];
  57001. /**
  57002. * An event triggered when the system is disposed.
  57003. */
  57004. this.onDisposeObservable = new BABYLON.Observable();
  57005. /**
  57006. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57007. */
  57008. this.updateSpeed = 0.01;
  57009. /**
  57010. * The amount of time the particle system is running (depends of the overall update speed).
  57011. */
  57012. this.targetStopDuration = 0;
  57013. /**
  57014. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57015. */
  57016. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57017. /**
  57018. * Minimum life time of emitting particles.
  57019. */
  57020. this.minLifeTime = 1;
  57021. /**
  57022. * Maximum life time of emitting particles.
  57023. */
  57024. this.maxLifeTime = 1;
  57025. /**
  57026. * Minimum Size of emitting particles.
  57027. */
  57028. this.minSize = 1;
  57029. /**
  57030. * Maximum Size of emitting particles.
  57031. */
  57032. this.maxSize = 1;
  57033. /**
  57034. * Minimum scale of emitting particles on X axis.
  57035. */
  57036. this.minScaleX = 1;
  57037. /**
  57038. * Maximum scale of emitting particles on X axis.
  57039. */
  57040. this.maxScaleX = 1;
  57041. /**
  57042. * Minimum scale of emitting particles on Y axis.
  57043. */
  57044. this.minScaleY = 1;
  57045. /**
  57046. * Maximum scale of emitting particles on Y axis.
  57047. */
  57048. this.maxScaleY = 1;
  57049. /**
  57050. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57051. */
  57052. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57053. /**
  57054. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57055. */
  57056. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57057. /**
  57058. * Color the particle will have at the end of its lifetime.
  57059. */
  57060. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57061. /**
  57062. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57063. */
  57064. this.emitRate = 100;
  57065. /**
  57066. * You can use gravity if you want to give an orientation to your particles.
  57067. */
  57068. this.gravity = BABYLON.Vector3.Zero();
  57069. /**
  57070. * Minimum power of emitting particles.
  57071. */
  57072. this.minEmitPower = 1;
  57073. /**
  57074. * Maximum power of emitting particles.
  57075. */
  57076. this.maxEmitPower = 1;
  57077. /**
  57078. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57079. */
  57080. this.minAngularSpeed = 0;
  57081. /**
  57082. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57083. */
  57084. this.maxAngularSpeed = 0;
  57085. /**
  57086. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57087. * to override the particles.
  57088. */
  57089. this.forceDepthWrite = false;
  57090. this._preWarmDone = false;
  57091. /** 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 */
  57092. this.preWarmCycles = 0;
  57093. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  57094. this.preWarmStepOffset = 1;
  57095. /**
  57096. * Gets or sets the minimal initial rotation in radians.
  57097. */
  57098. this.minInitialRotation = 0;
  57099. /**
  57100. * Gets or sets the maximal initial rotation in radians.
  57101. */
  57102. this.maxInitialRotation = 0;
  57103. /**
  57104. * 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)
  57105. */
  57106. this.spriteCellChangeSpeed = 1;
  57107. /**
  57108. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  57109. */
  57110. this.startSpriteCellID = 0;
  57111. /**
  57112. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  57113. */
  57114. this.endSpriteCellID = 0;
  57115. /**
  57116. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  57117. */
  57118. this.spriteCellWidth = 0;
  57119. /**
  57120. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  57121. */
  57122. this.spriteCellHeight = 0;
  57123. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  57124. this.translationPivot = new BABYLON.Vector2(0, 0);
  57125. /**
  57126. * Gets or sets the billboard mode to use when isBillboardBased = true.
  57127. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  57128. */
  57129. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  57130. this._isBillboardBased = true;
  57131. this._colorGradients = null;
  57132. this._angularSpeedGradients = null;
  57133. this._sizeGradients = null;
  57134. this._velocityGradients = null;
  57135. this.id = name;
  57136. this.name = name;
  57137. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57138. this._engine = this._scene.getEngine();
  57139. if (!options.randomTextureSize) {
  57140. delete options.randomTextureSize;
  57141. }
  57142. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57143. var optionsAsNumber = options;
  57144. if (isFinite(optionsAsNumber)) {
  57145. fullOptions.capacity = optionsAsNumber;
  57146. }
  57147. this._capacity = fullOptions.capacity;
  57148. this._activeCount = fullOptions.capacity;
  57149. this._currentActiveCount = 0;
  57150. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57151. this._scene.particleSystems.push(this);
  57152. this._updateEffectOptions = {
  57153. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  57154. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  57155. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57156. "angleRange", "radiusRange", "cellInfos"],
  57157. uniformBuffersNames: [],
  57158. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler"],
  57159. defines: "",
  57160. fallbacks: null,
  57161. onCompiled: null,
  57162. onError: null,
  57163. indexParameters: null,
  57164. maxSimultaneousLights: 0,
  57165. transformFeedbackVaryings: []
  57166. };
  57167. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57168. // Random data
  57169. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57170. var d = [];
  57171. for (var i = 0; i < maxTextureSize; ++i) {
  57172. d.push(Math.random());
  57173. d.push(Math.random());
  57174. d.push(Math.random());
  57175. d.push(Math.random());
  57176. }
  57177. 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);
  57178. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57179. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57180. d = [];
  57181. for (var i = 0; i < maxTextureSize; ++i) {
  57182. d.push(Math.random());
  57183. d.push(Math.random());
  57184. d.push(Math.random());
  57185. d.push(Math.random());
  57186. }
  57187. 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);
  57188. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57189. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57190. this._randomTextureSize = maxTextureSize;
  57191. }
  57192. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57193. /**
  57194. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57195. */
  57196. get: function () {
  57197. if (!BABYLON.Engine.LastCreatedEngine) {
  57198. return false;
  57199. }
  57200. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57201. },
  57202. enumerable: true,
  57203. configurable: true
  57204. });
  57205. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57206. /**
  57207. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57208. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57209. */
  57210. get: function () {
  57211. if (this.particleEmitterType.direction1) {
  57212. return this.particleEmitterType.direction1;
  57213. }
  57214. return BABYLON.Vector3.Zero();
  57215. },
  57216. set: function (value) {
  57217. if (this.particleEmitterType.direction1) {
  57218. this.particleEmitterType.direction1 = value;
  57219. }
  57220. },
  57221. enumerable: true,
  57222. configurable: true
  57223. });
  57224. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57225. /**
  57226. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57227. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57228. */
  57229. get: function () {
  57230. if (this.particleEmitterType.direction2) {
  57231. return this.particleEmitterType.direction2;
  57232. }
  57233. return BABYLON.Vector3.Zero();
  57234. },
  57235. set: function (value) {
  57236. if (this.particleEmitterType.direction2) {
  57237. this.particleEmitterType.direction2 = value;
  57238. }
  57239. },
  57240. enumerable: true,
  57241. configurable: true
  57242. });
  57243. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57244. /**
  57245. * 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.
  57246. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57247. */
  57248. get: function () {
  57249. if (this.particleEmitterType.minEmitBox) {
  57250. return this.particleEmitterType.minEmitBox;
  57251. }
  57252. return BABYLON.Vector3.Zero();
  57253. },
  57254. set: function (value) {
  57255. if (this.particleEmitterType.minEmitBox) {
  57256. this.particleEmitterType.minEmitBox = value;
  57257. }
  57258. },
  57259. enumerable: true,
  57260. configurable: true
  57261. });
  57262. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57263. /**
  57264. * 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.
  57265. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57266. */
  57267. get: function () {
  57268. if (this.particleEmitterType.maxEmitBox) {
  57269. return this.particleEmitterType.maxEmitBox;
  57270. }
  57271. return BABYLON.Vector3.Zero();
  57272. },
  57273. set: function (value) {
  57274. if (this.particleEmitterType.maxEmitBox) {
  57275. this.particleEmitterType.maxEmitBox = value;
  57276. }
  57277. },
  57278. enumerable: true,
  57279. configurable: true
  57280. });
  57281. /**
  57282. * Gets the maximum number of particles active at the same time.
  57283. * @returns The max number of active particles.
  57284. */
  57285. GPUParticleSystem.prototype.getCapacity = function () {
  57286. return this._capacity;
  57287. };
  57288. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57289. /**
  57290. * Gets or set the number of active particles
  57291. */
  57292. get: function () {
  57293. return this._activeCount;
  57294. },
  57295. set: function (value) {
  57296. this._activeCount = Math.min(value, this._capacity);
  57297. },
  57298. enumerable: true,
  57299. configurable: true
  57300. });
  57301. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  57302. /**
  57303. * Gets whether an animation sprite sheet is enabled or not on the particle system
  57304. */
  57305. get: function () {
  57306. return this._isAnimationSheetEnabled;
  57307. },
  57308. enumerable: true,
  57309. configurable: true
  57310. });
  57311. /**
  57312. * Is this system ready to be used/rendered
  57313. * @return true if the system is ready
  57314. */
  57315. GPUParticleSystem.prototype.isReady = function () {
  57316. if (!this._updateEffect) {
  57317. this._recreateUpdateEffect();
  57318. this._recreateRenderEffect();
  57319. return false;
  57320. }
  57321. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57322. return false;
  57323. }
  57324. return true;
  57325. };
  57326. /**
  57327. * Gets Wether the system has been started.
  57328. * @returns True if it has been started, otherwise false.
  57329. */
  57330. GPUParticleSystem.prototype.isStarted = function () {
  57331. return this._started;
  57332. };
  57333. /**
  57334. * Starts the particle system and begins to emit.
  57335. */
  57336. GPUParticleSystem.prototype.start = function () {
  57337. this._started = true;
  57338. this._stopped = false;
  57339. this._preWarmDone = false;
  57340. };
  57341. /**
  57342. * Stops the particle system.
  57343. */
  57344. GPUParticleSystem.prototype.stop = function () {
  57345. this._stopped = true;
  57346. };
  57347. /**
  57348. * Remove all active particles
  57349. */
  57350. GPUParticleSystem.prototype.reset = function () {
  57351. this._releaseBuffers();
  57352. this._releaseVAOs();
  57353. this._currentActiveCount = 0;
  57354. this._targetIndex = 0;
  57355. };
  57356. /**
  57357. * Returns the string "GPUParticleSystem"
  57358. * @returns a string containing the class name
  57359. */
  57360. GPUParticleSystem.prototype.getClassName = function () {
  57361. return "GPUParticleSystem";
  57362. };
  57363. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  57364. /**
  57365. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57366. */
  57367. get: function () {
  57368. return this._isBillboardBased;
  57369. },
  57370. set: function (value) {
  57371. if (this._isBillboardBased === value) {
  57372. return;
  57373. }
  57374. this._isBillboardBased = value;
  57375. this._releaseBuffers();
  57376. },
  57377. enumerable: true,
  57378. configurable: true
  57379. });
  57380. /**
  57381. * Gets the current list of color gradients.
  57382. * You must use addColorGradient and removeColorGradient to udpate this list
  57383. * @returns the list of color gradients
  57384. */
  57385. GPUParticleSystem.prototype.getColorGradients = function () {
  57386. return this._colorGradients;
  57387. };
  57388. /**
  57389. * Gets the current list of size gradients.
  57390. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57391. * @returns the list of size gradients
  57392. */
  57393. GPUParticleSystem.prototype.getSizeGradients = function () {
  57394. return this._sizeGradients;
  57395. };
  57396. /**
  57397. * Gets the current list of angular speed gradients.
  57398. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  57399. * @returns the list of angular speed gradients
  57400. */
  57401. GPUParticleSystem.prototype.getAngularSpeedGradients = function () {
  57402. return this._angularSpeedGradients;
  57403. };
  57404. /**
  57405. * Gets the current list of velocity gradients.
  57406. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  57407. * @returns the list of angular speed gradients
  57408. */
  57409. GPUParticleSystem.prototype.getVelocityGradients = function () {
  57410. return this._velocityGradients;
  57411. };
  57412. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  57413. if (!gradients) {
  57414. return this;
  57415. }
  57416. var index = 0;
  57417. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  57418. var valueGradient = gradients_1[_i];
  57419. if (valueGradient.gradient === gradient) {
  57420. gradients.splice(index, 1);
  57421. break;
  57422. }
  57423. index++;
  57424. }
  57425. if (texture) {
  57426. texture.dispose();
  57427. }
  57428. this._releaseBuffers();
  57429. return this;
  57430. };
  57431. /**
  57432. * Adds a new color gradient
  57433. * @param gradient defines the gradient to use (between 0 and 1)
  57434. * @param color defines the color to affect to the specified gradient
  57435. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  57436. * @returns the current particle system
  57437. */
  57438. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  57439. if (!this._colorGradients) {
  57440. this._colorGradients = [];
  57441. }
  57442. var colorGradient = new BABYLON.ColorGradient();
  57443. colorGradient.gradient = gradient;
  57444. colorGradient.color1 = color1;
  57445. this._colorGradients.push(colorGradient);
  57446. this._colorGradients.sort(function (a, b) {
  57447. if (a.gradient < b.gradient) {
  57448. return -1;
  57449. }
  57450. else if (a.gradient > b.gradient) {
  57451. return 1;
  57452. }
  57453. return 0;
  57454. });
  57455. if (this._colorGradientsTexture) {
  57456. this._colorGradientsTexture.dispose();
  57457. this._colorGradientsTexture = null;
  57458. }
  57459. this._releaseBuffers();
  57460. return this;
  57461. };
  57462. /**
  57463. * Remove a specific color gradient
  57464. * @param gradient defines the gradient to remove
  57465. * @returns the current particle system
  57466. */
  57467. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  57468. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  57469. this._colorGradientsTexture = null;
  57470. return this;
  57471. };
  57472. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  57473. var valueGradient = new BABYLON.FactorGradient();
  57474. valueGradient.gradient = gradient;
  57475. valueGradient.factor1 = factor;
  57476. factorGradients.push(valueGradient);
  57477. factorGradients.sort(function (a, b) {
  57478. if (a.gradient < b.gradient) {
  57479. return -1;
  57480. }
  57481. else if (a.gradient > b.gradient) {
  57482. return 1;
  57483. }
  57484. return 0;
  57485. });
  57486. this._releaseBuffers();
  57487. };
  57488. /**
  57489. * Adds a new size gradient
  57490. * @param gradient defines the gradient to use (between 0 and 1)
  57491. * @param factor defines the size factor to affect to the specified gradient
  57492. * @returns the current particle system
  57493. */
  57494. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  57495. if (!this._sizeGradients) {
  57496. this._sizeGradients = [];
  57497. }
  57498. this._addFactorGradient(this._sizeGradients, gradient, factor);
  57499. if (this._sizeGradientsTexture) {
  57500. this._sizeGradientsTexture.dispose();
  57501. this._sizeGradientsTexture = null;
  57502. }
  57503. this._releaseBuffers();
  57504. return this;
  57505. };
  57506. /**
  57507. * Remove a specific size gradient
  57508. * @param gradient defines the gradient to remove
  57509. * @returns the current particle system
  57510. */
  57511. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57512. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  57513. this._sizeGradientsTexture = null;
  57514. return this;
  57515. };
  57516. /**
  57517. * Adds a new angular speed gradient
  57518. * @param gradient defines the gradient to use (between 0 and 1)
  57519. * @param factor defines the size factor to affect to the specified gradient
  57520. * @returns the current particle system
  57521. */
  57522. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  57523. if (!this._angularSpeedGradients) {
  57524. this._angularSpeedGradients = [];
  57525. }
  57526. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  57527. if (this._angularSpeedGradientsTexture) {
  57528. this._angularSpeedGradientsTexture.dispose();
  57529. this._angularSpeedGradientsTexture = null;
  57530. }
  57531. this._releaseBuffers();
  57532. return this;
  57533. };
  57534. /**
  57535. * Remove a specific angular speed gradient
  57536. * @param gradient defines the gradient to remove
  57537. * @returns the current particle system
  57538. */
  57539. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  57540. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  57541. this._angularSpeedGradientsTexture = null;
  57542. return this;
  57543. };
  57544. /**
  57545. * Adds a new velocity gradient
  57546. * @param gradient defines the gradient to use (between 0 and 1)
  57547. * @param factor defines the size factor to affect to the specified gradient
  57548. * @returns the current particle system
  57549. */
  57550. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  57551. if (!this._velocityGradients) {
  57552. this._velocityGradients = [];
  57553. }
  57554. this._addFactorGradient(this._velocityGradients, gradient, factor);
  57555. if (this._velocityGradientsTexture) {
  57556. this._velocityGradientsTexture.dispose();
  57557. this._velocityGradientsTexture = null;
  57558. }
  57559. this._releaseBuffers();
  57560. return this;
  57561. };
  57562. /**
  57563. * Remove a specific velocity gradient
  57564. * @param gradient defines the gradient to remove
  57565. * @returns the current particle system
  57566. */
  57567. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  57568. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  57569. this._velocityGradientsTexture = null;
  57570. return this;
  57571. };
  57572. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57573. var updateVertexBuffers = {};
  57574. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57575. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57576. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57577. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  57578. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  57579. var offset = 12;
  57580. if (!this._colorGradientsTexture) {
  57581. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  57582. offset += 4;
  57583. }
  57584. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  57585. offset += 3;
  57586. if (!this._isBillboardBased) {
  57587. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  57588. offset += 3;
  57589. }
  57590. if (this._angularSpeedGradientsTexture) {
  57591. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  57592. offset += 1;
  57593. }
  57594. else {
  57595. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  57596. offset += 2;
  57597. }
  57598. if (this._isAnimationSheetEnabled) {
  57599. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  57600. offset += 1;
  57601. }
  57602. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57603. this._engine.bindArrayBuffer(null);
  57604. return vao;
  57605. };
  57606. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57607. var renderVertexBuffers = {};
  57608. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57609. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57610. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57611. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  57612. var offset = 12;
  57613. if (!this._colorGradientsTexture) {
  57614. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  57615. offset += 4;
  57616. }
  57617. offset += 3; // Direction
  57618. if (!this._isBillboardBased) {
  57619. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  57620. offset += 3;
  57621. }
  57622. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  57623. if (this._angularSpeedGradientsTexture) {
  57624. offset++;
  57625. }
  57626. else {
  57627. offset += 2;
  57628. }
  57629. if (this._isAnimationSheetEnabled) {
  57630. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  57631. offset += 1;
  57632. }
  57633. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57634. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57635. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57636. this._engine.bindArrayBuffer(null);
  57637. return vao;
  57638. };
  57639. GPUParticleSystem.prototype._initialize = function (force) {
  57640. if (force === void 0) { force = false; }
  57641. if (this._buffer0 && !force) {
  57642. return;
  57643. }
  57644. var engine = this._scene.getEngine();
  57645. var data = new Array();
  57646. if (!this.isBillboardBased) {
  57647. this._attributesStrideSize += 3;
  57648. }
  57649. if (this._colorGradientsTexture) {
  57650. this._attributesStrideSize -= 4;
  57651. }
  57652. if (this._angularSpeedGradientsTexture) {
  57653. this._attributesStrideSize -= 1;
  57654. }
  57655. if (this._isAnimationSheetEnabled) {
  57656. this._attributesStrideSize += 1;
  57657. }
  57658. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57659. // position
  57660. data.push(0.0);
  57661. data.push(0.0);
  57662. data.push(0.0);
  57663. // Age and life
  57664. data.push(0.0); // create the particle as a dead one to create a new one at start
  57665. data.push(0.0);
  57666. // Seed
  57667. data.push(Math.random());
  57668. data.push(Math.random());
  57669. data.push(Math.random());
  57670. data.push(Math.random());
  57671. // Size
  57672. data.push(0.0);
  57673. data.push(0.0);
  57674. data.push(0.0);
  57675. if (!this._colorGradientsTexture) {
  57676. // color
  57677. data.push(0.0);
  57678. data.push(0.0);
  57679. data.push(0.0);
  57680. data.push(0.0);
  57681. }
  57682. // direction
  57683. data.push(0.0);
  57684. data.push(0.0);
  57685. data.push(0.0);
  57686. if (!this.isBillboardBased) {
  57687. // initialDirection
  57688. data.push(0.0);
  57689. data.push(0.0);
  57690. data.push(0.0);
  57691. }
  57692. // angle
  57693. data.push(0.0);
  57694. if (!this._angularSpeedGradientsTexture) {
  57695. data.push(0.0);
  57696. }
  57697. if (this._isAnimationSheetEnabled) {
  57698. data.push(0.0);
  57699. }
  57700. }
  57701. // Sprite data
  57702. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57703. -0.5, 0.5, 0, 1,
  57704. -0.5, -0.5, 0, 0,
  57705. 0.5, -0.5, 1, 0]);
  57706. // Buffers
  57707. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57708. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57709. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57710. // Update VAO
  57711. this._updateVAO = [];
  57712. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57713. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57714. // Render VAO
  57715. this._renderVAO = [];
  57716. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57717. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57718. // Links
  57719. this._sourceBuffer = this._buffer0;
  57720. this._targetBuffer = this._buffer1;
  57721. };
  57722. /** @hidden */
  57723. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57724. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57725. if (this._isBillboardBased) {
  57726. defines += "\n#define BILLBOARD";
  57727. }
  57728. if (this._colorGradientsTexture) {
  57729. defines += "\n#define COLORGRADIENTS";
  57730. }
  57731. if (this._sizeGradientsTexture) {
  57732. defines += "\n#define SIZEGRADIENTS";
  57733. }
  57734. if (this._angularSpeedGradientsTexture) {
  57735. defines += "\n#define ANGULARSPEEDGRADIENTS";
  57736. }
  57737. if (this._velocityGradientsTexture) {
  57738. defines += "\n#define VELOCITYGRADIENTS";
  57739. }
  57740. if (this.isAnimationSheetEnabled) {
  57741. defines += "\n#define ANIMATESHEET";
  57742. }
  57743. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57744. return;
  57745. }
  57746. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  57747. if (!this._colorGradientsTexture) {
  57748. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  57749. }
  57750. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  57751. if (!this._isBillboardBased) {
  57752. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57753. }
  57754. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57755. if (this.isAnimationSheetEnabled) {
  57756. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  57757. }
  57758. this._updateEffectOptions.defines = defines;
  57759. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57760. };
  57761. /** @hidden */
  57762. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57763. var defines = "";
  57764. if (this._scene.clipPlane) {
  57765. defines = "\n#define CLIPPLANE";
  57766. }
  57767. if (this._isBillboardBased) {
  57768. defines += "\n#define BILLBOARD";
  57769. switch (this.billboardMode) {
  57770. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57771. defines += "\n#define BILLBOARDY";
  57772. break;
  57773. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57774. default:
  57775. break;
  57776. }
  57777. }
  57778. if (this._colorGradientsTexture) {
  57779. defines += "\n#define COLORGRADIENTS";
  57780. }
  57781. if (this.isAnimationSheetEnabled) {
  57782. defines += "\n#define ANIMATESHEET";
  57783. }
  57784. if (this._renderEffect && this._renderEffect.defines === defines) {
  57785. return;
  57786. }
  57787. 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);
  57788. };
  57789. /**
  57790. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57791. * @param preWarm defines if we are in the pre-warmimg phase
  57792. */
  57793. GPUParticleSystem.prototype.animate = function (preWarm) {
  57794. if (preWarm === void 0) { preWarm = false; }
  57795. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57796. this._actualFrame += this._timeDelta;
  57797. if (!this._stopped) {
  57798. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57799. this.stop();
  57800. }
  57801. }
  57802. };
  57803. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  57804. var texture = this[textureName];
  57805. if (!factorGradients || !factorGradients.length || texture) {
  57806. return;
  57807. }
  57808. var data = new Float32Array(this._rawTextureWidth);
  57809. for (var x = 0; x < this._rawTextureWidth; x++) {
  57810. var ratio = x / this._rawTextureWidth;
  57811. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  57812. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57813. });
  57814. }
  57815. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57816. };
  57817. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  57818. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  57819. };
  57820. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  57821. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  57822. };
  57823. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  57824. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  57825. };
  57826. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  57827. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  57828. return;
  57829. }
  57830. var data = new Uint8Array(this._rawTextureWidth * 4);
  57831. var tmpColor = BABYLON.Tmp.Color4[0];
  57832. for (var x = 0; x < this._rawTextureWidth; x++) {
  57833. var ratio = x / this._rawTextureWidth;
  57834. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  57835. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  57836. data[x * 4] = tmpColor.r * 255;
  57837. data[x * 4 + 1] = tmpColor.g * 255;
  57838. data[x * 4 + 2] = tmpColor.b * 255;
  57839. data[x * 4 + 3] = tmpColor.a * 255;
  57840. });
  57841. }
  57842. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57843. };
  57844. /**
  57845. * Renders the particle system in its current state
  57846. * @param preWarm defines if the system should only update the particles but not render them
  57847. * @returns the current number of particles
  57848. */
  57849. GPUParticleSystem.prototype.render = function (preWarm) {
  57850. if (preWarm === void 0) { preWarm = false; }
  57851. if (!this._started) {
  57852. return 0;
  57853. }
  57854. this._createColorGradientTexture();
  57855. this._createSizeGradientTexture();
  57856. this._createAngularSpeedGradientTexture();
  57857. this._createVelocityGradientTexture();
  57858. this._recreateUpdateEffect();
  57859. this._recreateRenderEffect();
  57860. if (!this.isReady()) {
  57861. return 0;
  57862. }
  57863. if (!preWarm) {
  57864. if (!this._preWarmDone && this.preWarmCycles) {
  57865. for (var index = 0; index < this.preWarmCycles; index++) {
  57866. this.animate(true);
  57867. this.render(true);
  57868. }
  57869. this._preWarmDone = true;
  57870. }
  57871. if (this._currentRenderId === this._scene.getRenderId()) {
  57872. return 0;
  57873. }
  57874. this._currentRenderId = this._scene.getRenderId();
  57875. }
  57876. // Get everything ready to render
  57877. this._initialize();
  57878. this._accumulatedCount += this.emitRate * this._timeDelta;
  57879. if (this._accumulatedCount > 1) {
  57880. var intPart = this._accumulatedCount | 0;
  57881. this._accumulatedCount -= intPart;
  57882. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  57883. }
  57884. if (!this._currentActiveCount) {
  57885. return 0;
  57886. }
  57887. // Enable update effect
  57888. this._engine.enableEffect(this._updateEffect);
  57889. this._engine.setState(false);
  57890. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57891. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57892. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57893. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57894. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  57895. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57896. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57897. if (!this._colorGradientsTexture) {
  57898. this._updateEffect.setDirectColor4("color1", this.color1);
  57899. this._updateEffect.setDirectColor4("color2", this.color2);
  57900. }
  57901. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57902. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  57903. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  57904. this._updateEffect.setVector3("gravity", this.gravity);
  57905. if (this._sizeGradientsTexture) {
  57906. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  57907. }
  57908. if (this._angularSpeedGradientsTexture) {
  57909. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  57910. }
  57911. if (this._velocityGradientsTexture) {
  57912. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  57913. }
  57914. if (this.particleEmitterType) {
  57915. this.particleEmitterType.applyToShader(this._updateEffect);
  57916. }
  57917. if (this._isAnimationSheetEnabled) {
  57918. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  57919. }
  57920. var emitterWM;
  57921. if (this.emitter.position) {
  57922. var emitterMesh = this.emitter;
  57923. emitterWM = emitterMesh.getWorldMatrix();
  57924. }
  57925. else {
  57926. var emitterPosition = this.emitter;
  57927. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57928. }
  57929. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57930. // Bind source VAO
  57931. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57932. // Update
  57933. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57934. this._engine.setRasterizerState(false);
  57935. this._engine.beginTransformFeedback();
  57936. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57937. this._engine.endTransformFeedback();
  57938. this._engine.setRasterizerState(true);
  57939. this._engine.bindTransformFeedbackBuffer(null);
  57940. if (!preWarm) {
  57941. // Enable render effect
  57942. this._engine.enableEffect(this._renderEffect);
  57943. var viewMatrix = this._scene.getViewMatrix();
  57944. this._renderEffect.setMatrix("view", viewMatrix);
  57945. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57946. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57947. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  57948. if (this._colorGradientsTexture) {
  57949. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  57950. }
  57951. else {
  57952. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57953. }
  57954. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57955. var baseSize = this.particleTexture.getBaseSize();
  57956. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57957. }
  57958. if (this._isBillboardBased) {
  57959. var camera = this._scene.activeCamera;
  57960. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  57961. }
  57962. if (this._scene.clipPlane) {
  57963. var clipPlane = this._scene.clipPlane;
  57964. var invView = viewMatrix.clone();
  57965. invView.invert();
  57966. this._renderEffect.setMatrix("invView", invView);
  57967. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57968. }
  57969. // Draw order
  57970. switch (this.blendMode) {
  57971. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  57972. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57973. break;
  57974. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  57975. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57976. break;
  57977. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  57978. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57979. break;
  57980. }
  57981. if (this.forceDepthWrite) {
  57982. this._engine.setDepthWrite(true);
  57983. }
  57984. // Bind source VAO
  57985. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57986. // Render
  57987. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57988. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57989. }
  57990. // Switch VAOs
  57991. this._targetIndex++;
  57992. if (this._targetIndex === 2) {
  57993. this._targetIndex = 0;
  57994. }
  57995. // Switch buffers
  57996. var tmpBuffer = this._sourceBuffer;
  57997. this._sourceBuffer = this._targetBuffer;
  57998. this._targetBuffer = tmpBuffer;
  57999. return this._currentActiveCount;
  58000. };
  58001. /**
  58002. * Rebuilds the particle system
  58003. */
  58004. GPUParticleSystem.prototype.rebuild = function () {
  58005. this._initialize(true);
  58006. };
  58007. GPUParticleSystem.prototype._releaseBuffers = function () {
  58008. if (this._buffer0) {
  58009. this._buffer0.dispose();
  58010. this._buffer0 = null;
  58011. }
  58012. if (this._buffer1) {
  58013. this._buffer1.dispose();
  58014. this._buffer1 = null;
  58015. }
  58016. if (this._spriteBuffer) {
  58017. this._spriteBuffer.dispose();
  58018. this._spriteBuffer = null;
  58019. }
  58020. };
  58021. GPUParticleSystem.prototype._releaseVAOs = function () {
  58022. if (!this._updateVAO) {
  58023. return;
  58024. }
  58025. for (var index = 0; index < this._updateVAO.length; index++) {
  58026. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58027. }
  58028. this._updateVAO = [];
  58029. for (var index = 0; index < this._renderVAO.length; index++) {
  58030. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58031. }
  58032. this._renderVAO = [];
  58033. };
  58034. /**
  58035. * Disposes the particle system and free the associated resources
  58036. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58037. */
  58038. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58039. if (disposeTexture === void 0) { disposeTexture = true; }
  58040. var index = this._scene.particleSystems.indexOf(this);
  58041. if (index > -1) {
  58042. this._scene.particleSystems.splice(index, 1);
  58043. }
  58044. this._releaseBuffers();
  58045. this._releaseVAOs();
  58046. if (this._colorGradientsTexture) {
  58047. this._colorGradientsTexture.dispose();
  58048. this._colorGradientsTexture = null;
  58049. }
  58050. if (this._sizeGradientsTexture) {
  58051. this._sizeGradientsTexture.dispose();
  58052. this._sizeGradientsTexture = null;
  58053. }
  58054. if (this._angularSpeedGradientsTexture) {
  58055. this._angularSpeedGradientsTexture.dispose();
  58056. this._angularSpeedGradientsTexture = null;
  58057. }
  58058. if (this._velocityGradientsTexture) {
  58059. this._velocityGradientsTexture.dispose();
  58060. this._velocityGradientsTexture = null;
  58061. }
  58062. if (this._randomTexture) {
  58063. this._randomTexture.dispose();
  58064. this._randomTexture = null;
  58065. }
  58066. if (this._randomTexture2) {
  58067. this._randomTexture2.dispose();
  58068. this._randomTexture2 = null;
  58069. }
  58070. if (disposeTexture && this.particleTexture) {
  58071. this.particleTexture.dispose();
  58072. this.particleTexture = null;
  58073. }
  58074. // Callback
  58075. this.onDisposeObservable.notifyObservers(this);
  58076. this.onDisposeObservable.clear();
  58077. };
  58078. /**
  58079. * Clones the particle system.
  58080. * @param name The name of the cloned object
  58081. * @param newEmitter The new emitter to use
  58082. * @returns the cloned particle system
  58083. */
  58084. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58085. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58086. BABYLON.Tools.DeepCopy(this, result);
  58087. if (newEmitter === undefined) {
  58088. newEmitter = this.emitter;
  58089. }
  58090. result.emitter = newEmitter;
  58091. if (this.particleTexture) {
  58092. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58093. }
  58094. return result;
  58095. };
  58096. /**
  58097. * Serializes the particle system to a JSON object.
  58098. * @returns the JSON object
  58099. */
  58100. GPUParticleSystem.prototype.serialize = function () {
  58101. var serializationObject = {};
  58102. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  58103. serializationObject.activeParticleCount = this.activeParticleCount;
  58104. return serializationObject;
  58105. };
  58106. /**
  58107. * Parses a JSON object to create a GPU particle system.
  58108. * @param parsedParticleSystem The JSON object to parse
  58109. * @param scene The scene to create the particle system in
  58110. * @param rootUrl The root url to use to load external dependencies like texture
  58111. * @returns the parsed GPU particle system
  58112. */
  58113. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58114. var name = parsedParticleSystem.name;
  58115. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58116. if (parsedParticleSystem.activeParticleCount) {
  58117. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58118. }
  58119. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  58120. return particleSystem;
  58121. };
  58122. return GPUParticleSystem;
  58123. }());
  58124. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58125. })(BABYLON || (BABYLON = {}));
  58126. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58127. var BABYLON;
  58128. (function (BABYLON) {
  58129. /**
  58130. * Represents one particle of a solid particle system.
  58131. */
  58132. var SolidParticle = /** @class */ (function () {
  58133. /**
  58134. * Creates a Solid Particle object.
  58135. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58136. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58137. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58138. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58139. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58140. * @param shapeId (integer) is the model shape identifier in the SPS.
  58141. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58142. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58143. */
  58144. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58145. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58146. /**
  58147. * particle global index
  58148. */
  58149. this.idx = 0;
  58150. /**
  58151. * The color of the particle
  58152. */
  58153. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58154. /**
  58155. * The world space position of the particle.
  58156. */
  58157. this.position = BABYLON.Vector3.Zero();
  58158. /**
  58159. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58160. */
  58161. this.rotation = BABYLON.Vector3.Zero();
  58162. /**
  58163. * The scaling of the particle.
  58164. */
  58165. this.scaling = BABYLON.Vector3.One();
  58166. /**
  58167. * The uvs of the particle.
  58168. */
  58169. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58170. /**
  58171. * The current speed of the particle.
  58172. */
  58173. this.velocity = BABYLON.Vector3.Zero();
  58174. /**
  58175. * The pivot point in the particle local space.
  58176. */
  58177. this.pivot = BABYLON.Vector3.Zero();
  58178. /**
  58179. * Must the particle be translated from its pivot point in its local space ?
  58180. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58181. * Default : false
  58182. */
  58183. this.translateFromPivot = false;
  58184. /**
  58185. * Is the particle active or not ?
  58186. */
  58187. this.alive = true;
  58188. /**
  58189. * Is the particle visible or not ?
  58190. */
  58191. this.isVisible = true;
  58192. /**
  58193. * Index of this particle in the global "positions" array (Internal use)
  58194. */
  58195. this._pos = 0;
  58196. /**
  58197. * Index of this particle in the global "indices" array (Internal use)
  58198. */
  58199. this._ind = 0;
  58200. /**
  58201. * ModelShape id of this particle
  58202. */
  58203. this.shapeId = 0;
  58204. /**
  58205. * Index of the particle in its shape id (Internal use)
  58206. */
  58207. this.idxInShape = 0;
  58208. /**
  58209. * Still set as invisible in order to skip useless computations (Internal use)
  58210. */
  58211. this._stillInvisible = false;
  58212. /**
  58213. * Last computed particle rotation matrix
  58214. */
  58215. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58216. /**
  58217. * Parent particle Id, if any.
  58218. * Default null.
  58219. */
  58220. this.parentId = null;
  58221. /**
  58222. * Internal global position in the SPS.
  58223. */
  58224. this._globalPosition = BABYLON.Vector3.Zero();
  58225. this.idx = particleIndex;
  58226. this._pos = positionIndex;
  58227. this._ind = indiceIndex;
  58228. this._model = model;
  58229. this.shapeId = shapeId;
  58230. this.idxInShape = idxInShape;
  58231. this._sps = sps;
  58232. if (modelBoundingInfo) {
  58233. this._modelBoundingInfo = modelBoundingInfo;
  58234. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58235. }
  58236. }
  58237. Object.defineProperty(SolidParticle.prototype, "scale", {
  58238. /**
  58239. * Legacy support, changed scale to scaling
  58240. */
  58241. get: function () {
  58242. return this.scaling;
  58243. },
  58244. /**
  58245. * Legacy support, changed scale to scaling
  58246. */
  58247. set: function (scale) {
  58248. this.scaling = scale;
  58249. },
  58250. enumerable: true,
  58251. configurable: true
  58252. });
  58253. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58254. /**
  58255. * Legacy support, changed quaternion to rotationQuaternion
  58256. */
  58257. get: function () {
  58258. return this.rotationQuaternion;
  58259. },
  58260. /**
  58261. * Legacy support, changed quaternion to rotationQuaternion
  58262. */
  58263. set: function (q) {
  58264. this.rotationQuaternion = q;
  58265. },
  58266. enumerable: true,
  58267. configurable: true
  58268. });
  58269. /**
  58270. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58271. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58272. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58273. * @returns true if it intersects
  58274. */
  58275. SolidParticle.prototype.intersectsMesh = function (target) {
  58276. if (!this._boundingInfo || !target._boundingInfo) {
  58277. return false;
  58278. }
  58279. if (this._sps._bSphereOnly) {
  58280. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58281. }
  58282. return this._boundingInfo.intersects(target._boundingInfo, false);
  58283. };
  58284. return SolidParticle;
  58285. }());
  58286. BABYLON.SolidParticle = SolidParticle;
  58287. /**
  58288. * Represents the shape of the model used by one particle of a solid particle system.
  58289. * SPS internal tool, don't use it manually.
  58290. */
  58291. var ModelShape = /** @class */ (function () {
  58292. /**
  58293. * 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.
  58294. * SPS internal tool, don't use it manually.
  58295. * @hidden
  58296. */
  58297. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58298. /**
  58299. * length of the shape in the model indices array (internal use)
  58300. */
  58301. this._indicesLength = 0;
  58302. this.shapeID = id;
  58303. this._shape = shape;
  58304. this._indicesLength = indicesLength;
  58305. this._shapeUV = shapeUV;
  58306. this._positionFunction = posFunction;
  58307. this._vertexFunction = vtxFunction;
  58308. }
  58309. return ModelShape;
  58310. }());
  58311. BABYLON.ModelShape = ModelShape;
  58312. /**
  58313. * Represents a Depth Sorted Particle in the solid particle system.
  58314. */
  58315. var DepthSortedParticle = /** @class */ (function () {
  58316. function DepthSortedParticle() {
  58317. /**
  58318. * Index of the particle in the "indices" array
  58319. */
  58320. this.ind = 0;
  58321. /**
  58322. * Length of the particle shape in the "indices" array
  58323. */
  58324. this.indicesLength = 0;
  58325. /**
  58326. * Squared distance from the particle to the camera
  58327. */
  58328. this.sqDistance = 0.0;
  58329. }
  58330. return DepthSortedParticle;
  58331. }());
  58332. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58333. })(BABYLON || (BABYLON = {}));
  58334. //# sourceMappingURL=babylon.solidParticle.js.map
  58335. var BABYLON;
  58336. (function (BABYLON) {
  58337. /**
  58338. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58339. *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.
  58340. * The SPS is also a particle system. It provides some methods to manage the particles.
  58341. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58342. *
  58343. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58344. */
  58345. var SolidParticleSystem = /** @class */ (function () {
  58346. /**
  58347. * Creates a SPS (Solid Particle System) object.
  58348. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58349. * @param scene (Scene) is the scene in which the SPS is added.
  58350. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58351. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58352. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58353. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58354. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58355. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58356. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58357. */
  58358. function SolidParticleSystem(name, scene, options) {
  58359. /**
  58360. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58361. * Example : var p = SPS.particles[i];
  58362. */
  58363. this.particles = new Array();
  58364. /**
  58365. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58366. */
  58367. this.nbParticles = 0;
  58368. /**
  58369. * If the particles must ever face the camera (default false). Useful for planar particles.
  58370. */
  58371. this.billboard = false;
  58372. /**
  58373. * Recompute normals when adding a shape
  58374. */
  58375. this.recomputeNormals = true;
  58376. /**
  58377. * This a counter ofr your own usage. It's not set by any SPS functions.
  58378. */
  58379. this.counter = 0;
  58380. /**
  58381. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58382. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58383. */
  58384. this.vars = {};
  58385. /**
  58386. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58387. */
  58388. this._bSphereOnly = false;
  58389. /**
  58390. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58391. */
  58392. this._bSphereRadiusFactor = 1.0;
  58393. this._positions = new Array();
  58394. this._indices = new Array();
  58395. this._normals = new Array();
  58396. this._colors = new Array();
  58397. this._uvs = new Array();
  58398. this._index = 0; // indices index
  58399. this._updatable = true;
  58400. this._pickable = false;
  58401. this._isVisibilityBoxLocked = false;
  58402. this._alwaysVisible = false;
  58403. this._depthSort = false;
  58404. this._shapeCounter = 0;
  58405. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58406. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58407. this._computeParticleColor = true;
  58408. this._computeParticleTexture = true;
  58409. this._computeParticleRotation = true;
  58410. this._computeParticleVertex = false;
  58411. this._computeBoundingBox = false;
  58412. this._depthSortParticles = true;
  58413. this._cam_axisZ = BABYLON.Vector3.Zero();
  58414. this._cam_axisY = BABYLON.Vector3.Zero();
  58415. this._cam_axisX = BABYLON.Vector3.Zero();
  58416. this._axisZ = BABYLON.Axis.Z;
  58417. this._camDir = BABYLON.Vector3.Zero();
  58418. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58419. this._rotMatrix = new BABYLON.Matrix();
  58420. this._invertMatrix = new BABYLON.Matrix();
  58421. this._rotated = BABYLON.Vector3.Zero();
  58422. this._quaternion = new BABYLON.Quaternion();
  58423. this._vertex = BABYLON.Vector3.Zero();
  58424. this._normal = BABYLON.Vector3.Zero();
  58425. this._yaw = 0.0;
  58426. this._pitch = 0.0;
  58427. this._roll = 0.0;
  58428. this._halfroll = 0.0;
  58429. this._halfpitch = 0.0;
  58430. this._halfyaw = 0.0;
  58431. this._sinRoll = 0.0;
  58432. this._cosRoll = 0.0;
  58433. this._sinPitch = 0.0;
  58434. this._cosPitch = 0.0;
  58435. this._sinYaw = 0.0;
  58436. this._cosYaw = 0.0;
  58437. this._mustUnrotateFixedNormals = false;
  58438. this._minimum = BABYLON.Vector3.Zero();
  58439. this._maximum = BABYLON.Vector3.Zero();
  58440. this._minBbox = BABYLON.Vector3.Zero();
  58441. this._maxBbox = BABYLON.Vector3.Zero();
  58442. this._particlesIntersect = false;
  58443. this._depthSortFunction = function (p1, p2) {
  58444. return (p2.sqDistance - p1.sqDistance);
  58445. };
  58446. this._needs32Bits = false;
  58447. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58448. this._scaledPivot = BABYLON.Vector3.Zero();
  58449. this._particleHasParent = false;
  58450. this.name = name;
  58451. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58452. this._camera = scene.activeCamera;
  58453. this._pickable = options ? options.isPickable : false;
  58454. this._depthSort = options ? options.enableDepthSort : false;
  58455. this._particlesIntersect = options ? options.particleIntersection : false;
  58456. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58457. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58458. if (options && options.updatable !== undefined) {
  58459. this._updatable = options.updatable;
  58460. }
  58461. else {
  58462. this._updatable = true;
  58463. }
  58464. if (this._pickable) {
  58465. this.pickedParticles = [];
  58466. }
  58467. if (this._depthSort) {
  58468. this.depthSortedParticles = [];
  58469. }
  58470. }
  58471. /**
  58472. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58473. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58474. * @returns the created mesh
  58475. */
  58476. SolidParticleSystem.prototype.buildMesh = function () {
  58477. if (this.nbParticles === 0) {
  58478. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58479. this.addShape(triangle, 1);
  58480. triangle.dispose();
  58481. }
  58482. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58483. this._positions32 = new Float32Array(this._positions);
  58484. this._uvs32 = new Float32Array(this._uvs);
  58485. this._colors32 = new Float32Array(this._colors);
  58486. if (this.recomputeNormals) {
  58487. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58488. }
  58489. this._normals32 = new Float32Array(this._normals);
  58490. this._fixedNormal32 = new Float32Array(this._normals);
  58491. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58492. this._unrotateFixedNormals();
  58493. }
  58494. var vertexData = new BABYLON.VertexData();
  58495. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58496. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58497. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58498. if (this._uvs32.length > 0) {
  58499. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58500. }
  58501. if (this._colors32.length > 0) {
  58502. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58503. }
  58504. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58505. vertexData.applyToMesh(mesh, this._updatable);
  58506. this.mesh = mesh;
  58507. this.mesh.isPickable = this._pickable;
  58508. // free memory
  58509. if (!this._depthSort) {
  58510. this._indices = null;
  58511. }
  58512. this._positions = null;
  58513. this._normals = null;
  58514. this._uvs = null;
  58515. this._colors = null;
  58516. if (!this._updatable) {
  58517. this.particles.length = 0;
  58518. }
  58519. return mesh;
  58520. };
  58521. /**
  58522. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58523. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58524. * Thus the particles generated from `digest()` have their property `position` set yet.
  58525. * @param mesh ( Mesh ) is the mesh to be digested
  58526. * @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
  58527. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58528. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58529. * @returns the current SPS
  58530. */
  58531. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58532. var size = (options && options.facetNb) || 1;
  58533. var number = (options && options.number) || 0;
  58534. var delta = (options && options.delta) || 0;
  58535. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58536. var meshInd = mesh.getIndices();
  58537. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58538. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58539. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58540. var f = 0; // facet counter
  58541. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58542. // compute size from number
  58543. if (number) {
  58544. number = (number > totalFacets) ? totalFacets : number;
  58545. size = Math.round(totalFacets / number);
  58546. delta = 0;
  58547. }
  58548. else {
  58549. size = (size > totalFacets) ? totalFacets : size;
  58550. }
  58551. var facetPos = []; // submesh positions
  58552. var facetInd = []; // submesh indices
  58553. var facetUV = []; // submesh UV
  58554. var facetCol = []; // submesh colors
  58555. var barycenter = BABYLON.Vector3.Zero();
  58556. var sizeO = size;
  58557. while (f < totalFacets) {
  58558. size = sizeO + Math.floor((1 + delta) * Math.random());
  58559. if (f > totalFacets - size) {
  58560. size = totalFacets - f;
  58561. }
  58562. // reset temp arrays
  58563. facetPos.length = 0;
  58564. facetInd.length = 0;
  58565. facetUV.length = 0;
  58566. facetCol.length = 0;
  58567. // iterate over "size" facets
  58568. var fi = 0;
  58569. for (var j = f * 3; j < (f + size) * 3; j++) {
  58570. facetInd.push(fi);
  58571. var i = meshInd[j];
  58572. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58573. if (meshUV) {
  58574. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58575. }
  58576. if (meshCol) {
  58577. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58578. }
  58579. fi++;
  58580. }
  58581. // create a model shape for each single particle
  58582. var idx = this.nbParticles;
  58583. var shape = this._posToShape(facetPos);
  58584. var shapeUV = this._uvsToShapeUV(facetUV);
  58585. // compute the barycenter of the shape
  58586. var v;
  58587. for (v = 0; v < shape.length; v++) {
  58588. barycenter.addInPlace(shape[v]);
  58589. }
  58590. barycenter.scaleInPlace(1 / shape.length);
  58591. // shift the shape from its barycenter to the origin
  58592. for (v = 0; v < shape.length; v++) {
  58593. shape[v].subtractInPlace(barycenter);
  58594. }
  58595. var bInfo;
  58596. if (this._particlesIntersect) {
  58597. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58598. }
  58599. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58600. // add the particle in the SPS
  58601. var currentPos = this._positions.length;
  58602. var currentInd = this._indices.length;
  58603. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58604. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58605. // initialize the particle position
  58606. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58607. this._index += shape.length;
  58608. idx++;
  58609. this.nbParticles++;
  58610. this._shapeCounter++;
  58611. f += size;
  58612. }
  58613. return this;
  58614. };
  58615. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58616. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58617. var index = 0;
  58618. var idx = 0;
  58619. for (var p = 0; p < this.particles.length; p++) {
  58620. this._particle = this.particles[p];
  58621. this._shape = this._particle._model._shape;
  58622. if (this._particle.rotationQuaternion) {
  58623. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58624. }
  58625. else {
  58626. this._yaw = this._particle.rotation.y;
  58627. this._pitch = this._particle.rotation.x;
  58628. this._roll = this._particle.rotation.z;
  58629. this._quaternionRotationYPR();
  58630. }
  58631. this._quaternionToRotationMatrix();
  58632. this._rotMatrix.invertToRef(this._invertMatrix);
  58633. for (var pt = 0; pt < this._shape.length; pt++) {
  58634. idx = index + pt * 3;
  58635. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58636. this._fixedNormal32[idx] = this._normal.x;
  58637. this._fixedNormal32[idx + 1] = this._normal.y;
  58638. this._fixedNormal32[idx + 2] = this._normal.z;
  58639. }
  58640. index = idx + 3;
  58641. }
  58642. };
  58643. //reset copy
  58644. SolidParticleSystem.prototype._resetCopy = function () {
  58645. this._copy.position.x = 0;
  58646. this._copy.position.y = 0;
  58647. this._copy.position.z = 0;
  58648. this._copy.rotation.x = 0;
  58649. this._copy.rotation.y = 0;
  58650. this._copy.rotation.z = 0;
  58651. this._copy.rotationQuaternion = null;
  58652. this._copy.scaling.x = 1.0;
  58653. this._copy.scaling.y = 1.0;
  58654. this._copy.scaling.z = 1.0;
  58655. this._copy.uvs.x = 0;
  58656. this._copy.uvs.y = 0;
  58657. this._copy.uvs.z = 1.0;
  58658. this._copy.uvs.w = 1.0;
  58659. this._copy.color = null;
  58660. this._copy.translateFromPivot = false;
  58661. };
  58662. // _meshBuilder : inserts the shape model in the global SPS mesh
  58663. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58664. var i;
  58665. var u = 0;
  58666. var c = 0;
  58667. var n = 0;
  58668. this._resetCopy();
  58669. if (options && options.positionFunction) { // call to custom positionFunction
  58670. options.positionFunction(this._copy, idx, idxInShape);
  58671. this._mustUnrotateFixedNormals = true;
  58672. }
  58673. if (this._copy.rotationQuaternion) {
  58674. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58675. }
  58676. else {
  58677. this._yaw = this._copy.rotation.y;
  58678. this._pitch = this._copy.rotation.x;
  58679. this._roll = this._copy.rotation.z;
  58680. this._quaternionRotationYPR();
  58681. }
  58682. this._quaternionToRotationMatrix();
  58683. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58684. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58685. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58686. if (this._copy.translateFromPivot) {
  58687. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58688. }
  58689. else {
  58690. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58691. }
  58692. for (i = 0; i < shape.length; i++) {
  58693. this._vertex.x = shape[i].x;
  58694. this._vertex.y = shape[i].y;
  58695. this._vertex.z = shape[i].z;
  58696. if (options && options.vertexFunction) {
  58697. options.vertexFunction(this._copy, this._vertex, i);
  58698. }
  58699. this._vertex.x *= this._copy.scaling.x;
  58700. this._vertex.y *= this._copy.scaling.y;
  58701. this._vertex.z *= this._copy.scaling.z;
  58702. this._vertex.x -= this._scaledPivot.x;
  58703. this._vertex.y -= this._scaledPivot.y;
  58704. this._vertex.z -= this._scaledPivot.z;
  58705. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58706. this._rotated.addInPlace(this._pivotBackTranslation);
  58707. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58708. if (meshUV) {
  58709. 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);
  58710. u += 2;
  58711. }
  58712. if (this._copy.color) {
  58713. this._color = this._copy.color;
  58714. }
  58715. else if (meshCol && meshCol[c] !== undefined) {
  58716. this._color.r = meshCol[c];
  58717. this._color.g = meshCol[c + 1];
  58718. this._color.b = meshCol[c + 2];
  58719. this._color.a = meshCol[c + 3];
  58720. }
  58721. else {
  58722. this._color.r = 1.0;
  58723. this._color.g = 1.0;
  58724. this._color.b = 1.0;
  58725. this._color.a = 1.0;
  58726. }
  58727. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58728. c += 4;
  58729. if (!this.recomputeNormals && meshNor) {
  58730. this._normal.x = meshNor[n];
  58731. this._normal.y = meshNor[n + 1];
  58732. this._normal.z = meshNor[n + 2];
  58733. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58734. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58735. n += 3;
  58736. }
  58737. }
  58738. for (i = 0; i < meshInd.length; i++) {
  58739. var current_ind = p + meshInd[i];
  58740. indices.push(current_ind);
  58741. if (current_ind > 65535) {
  58742. this._needs32Bits = true;
  58743. }
  58744. }
  58745. if (this._pickable) {
  58746. var nbfaces = meshInd.length / 3;
  58747. for (i = 0; i < nbfaces; i++) {
  58748. this.pickedParticles.push({ idx: idx, faceId: i });
  58749. }
  58750. }
  58751. if (this._depthSort) {
  58752. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58753. }
  58754. return this._copy;
  58755. };
  58756. // returns a shape array from positions array
  58757. SolidParticleSystem.prototype._posToShape = function (positions) {
  58758. var shape = [];
  58759. for (var i = 0; i < positions.length; i += 3) {
  58760. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58761. }
  58762. return shape;
  58763. };
  58764. // returns a shapeUV array from a Vector4 uvs
  58765. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58766. var shapeUV = [];
  58767. if (uvs) {
  58768. for (var i = 0; i < uvs.length; i++)
  58769. shapeUV.push(uvs[i]);
  58770. }
  58771. return shapeUV;
  58772. };
  58773. // adds a new particle object in the particles array
  58774. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58775. if (bInfo === void 0) { bInfo = null; }
  58776. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58777. this.particles.push(sp);
  58778. return sp;
  58779. };
  58780. /**
  58781. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58782. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58783. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58784. * @param nb (positive integer) the number of particles to be created from this model
  58785. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58786. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58787. * @returns the number of shapes in the system
  58788. */
  58789. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58790. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58791. var meshInd = mesh.getIndices();
  58792. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58793. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58794. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58795. var bbInfo;
  58796. if (this._particlesIntersect) {
  58797. bbInfo = mesh.getBoundingInfo();
  58798. }
  58799. var shape = this._posToShape(meshPos);
  58800. var shapeUV = this._uvsToShapeUV(meshUV);
  58801. var posfunc = options ? options.positionFunction : null;
  58802. var vtxfunc = options ? options.vertexFunction : null;
  58803. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58804. // particles
  58805. var sp;
  58806. var currentCopy;
  58807. var idx = this.nbParticles;
  58808. for (var i = 0; i < nb; i++) {
  58809. var currentPos = this._positions.length;
  58810. var currentInd = this._indices.length;
  58811. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58812. if (this._updatable) {
  58813. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58814. sp.position.copyFrom(currentCopy.position);
  58815. sp.rotation.copyFrom(currentCopy.rotation);
  58816. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58817. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58818. }
  58819. if (currentCopy.color && sp.color) {
  58820. sp.color.copyFrom(currentCopy.color);
  58821. }
  58822. sp.scaling.copyFrom(currentCopy.scaling);
  58823. sp.uvs.copyFrom(currentCopy.uvs);
  58824. }
  58825. this._index += shape.length;
  58826. idx++;
  58827. }
  58828. this.nbParticles += nb;
  58829. this._shapeCounter++;
  58830. return this._shapeCounter - 1;
  58831. };
  58832. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58833. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58834. this._resetCopy();
  58835. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58836. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58837. }
  58838. if (this._copy.rotationQuaternion) {
  58839. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58840. }
  58841. else {
  58842. this._yaw = this._copy.rotation.y;
  58843. this._pitch = this._copy.rotation.x;
  58844. this._roll = this._copy.rotation.z;
  58845. this._quaternionRotationYPR();
  58846. }
  58847. this._quaternionToRotationMatrix();
  58848. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58849. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58850. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58851. if (this._copy.translateFromPivot) {
  58852. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58853. }
  58854. else {
  58855. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58856. }
  58857. this._shape = particle._model._shape;
  58858. for (var pt = 0; pt < this._shape.length; pt++) {
  58859. this._vertex.x = this._shape[pt].x;
  58860. this._vertex.y = this._shape[pt].y;
  58861. this._vertex.z = this._shape[pt].z;
  58862. if (particle._model._vertexFunction) {
  58863. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58864. }
  58865. this._vertex.x *= this._copy.scaling.x;
  58866. this._vertex.y *= this._copy.scaling.y;
  58867. this._vertex.z *= this._copy.scaling.z;
  58868. this._vertex.x -= this._scaledPivot.x;
  58869. this._vertex.y -= this._scaledPivot.y;
  58870. this._vertex.z -= this._scaledPivot.z;
  58871. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58872. this._rotated.addInPlace(this._pivotBackTranslation);
  58873. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58874. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58875. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58876. }
  58877. particle.position.x = 0.0;
  58878. particle.position.y = 0.0;
  58879. particle.position.z = 0.0;
  58880. particle.rotation.x = 0.0;
  58881. particle.rotation.y = 0.0;
  58882. particle.rotation.z = 0.0;
  58883. particle.rotationQuaternion = null;
  58884. particle.scaling.x = 1.0;
  58885. particle.scaling.y = 1.0;
  58886. particle.scaling.z = 1.0;
  58887. particle.uvs.x = 0.0;
  58888. particle.uvs.y = 0.0;
  58889. particle.uvs.z = 1.0;
  58890. particle.uvs.w = 1.0;
  58891. particle.pivot.x = 0.0;
  58892. particle.pivot.y = 0.0;
  58893. particle.pivot.z = 0.0;
  58894. particle.translateFromPivot = false;
  58895. particle.parentId = null;
  58896. };
  58897. /**
  58898. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58899. * @returns the SPS.
  58900. */
  58901. SolidParticleSystem.prototype.rebuildMesh = function () {
  58902. for (var p = 0; p < this.particles.length; p++) {
  58903. this._rebuildParticle(this.particles[p]);
  58904. }
  58905. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58906. return this;
  58907. };
  58908. /**
  58909. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58910. * This method calls `updateParticle()` for each particle of the SPS.
  58911. * For an animated SPS, it is usually called within the render loop.
  58912. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58913. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58914. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58915. * @returns the SPS.
  58916. */
  58917. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58918. if (start === void 0) { start = 0; }
  58919. if (end === void 0) { end = this.nbParticles - 1; }
  58920. if (update === void 0) { update = true; }
  58921. if (!this._updatable) {
  58922. return this;
  58923. }
  58924. // custom beforeUpdate
  58925. this.beforeUpdateParticles(start, end, update);
  58926. this._cam_axisX.x = 1.0;
  58927. this._cam_axisX.y = 0.0;
  58928. this._cam_axisX.z = 0.0;
  58929. this._cam_axisY.x = 0.0;
  58930. this._cam_axisY.y = 1.0;
  58931. this._cam_axisY.z = 0.0;
  58932. this._cam_axisZ.x = 0.0;
  58933. this._cam_axisZ.y = 0.0;
  58934. this._cam_axisZ.z = 1.0;
  58935. // cases when the World Matrix is to be computed first
  58936. if (this.billboard || this._depthSort) {
  58937. this.mesh.computeWorldMatrix(true);
  58938. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58939. }
  58940. // if the particles will always face the camera
  58941. if (this.billboard) {
  58942. // compute the camera position and un-rotate it by the current mesh rotation
  58943. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58944. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58945. this._cam_axisZ.normalize();
  58946. // same for camera up vector extracted from the cam view matrix
  58947. var view = this._camera.getViewMatrix(true);
  58948. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58949. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58950. this._cam_axisY.normalize();
  58951. this._cam_axisX.normalize();
  58952. }
  58953. // if depthSort, compute the camera global position in the mesh local system
  58954. if (this._depthSort) {
  58955. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58956. }
  58957. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58958. var idx = 0; // current position index in the global array positions32
  58959. var index = 0; // position start index in the global array positions32 of the current particle
  58960. var colidx = 0; // current color index in the global array colors32
  58961. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58962. var uvidx = 0; // current uv index in the global array uvs32
  58963. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58964. var pt = 0; // current index in the particle model shape
  58965. if (this.mesh.isFacetDataEnabled) {
  58966. this._computeBoundingBox = true;
  58967. }
  58968. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58969. if (this._computeBoundingBox) {
  58970. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58971. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58972. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58973. }
  58974. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58975. if (this.mesh._boundingInfo) {
  58976. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58977. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58978. }
  58979. }
  58980. }
  58981. // particle loop
  58982. index = this.particles[start]._pos;
  58983. var vpos = (index / 3) | 0;
  58984. colorIndex = vpos * 4;
  58985. uvIndex = vpos * 2;
  58986. for (var p = start; p <= end; p++) {
  58987. this._particle = this.particles[p];
  58988. this._shape = this._particle._model._shape;
  58989. this._shapeUV = this._particle._model._shapeUV;
  58990. // call to custom user function to update the particle properties
  58991. this.updateParticle(this._particle);
  58992. // camera-particle distance for depth sorting
  58993. if (this._depthSort && this._depthSortParticles) {
  58994. var dsp = this.depthSortedParticles[p];
  58995. dsp.ind = this._particle._ind;
  58996. dsp.indicesLength = this._particle._model._indicesLength;
  58997. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58998. }
  58999. // skip the computations for inactive or already invisible particles
  59000. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59001. // increment indexes for the next particle
  59002. pt = this._shape.length;
  59003. index += pt * 3;
  59004. colorIndex += pt * 4;
  59005. uvIndex += pt * 2;
  59006. continue;
  59007. }
  59008. if (this._particle.isVisible) {
  59009. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59010. this._particleHasParent = (this._particle.parentId !== null);
  59011. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59012. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59013. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59014. // particle rotation matrix
  59015. if (this.billboard) {
  59016. this._particle.rotation.x = 0.0;
  59017. this._particle.rotation.y = 0.0;
  59018. }
  59019. if (this._computeParticleRotation || this.billboard) {
  59020. if (this._particle.rotationQuaternion) {
  59021. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59022. }
  59023. else {
  59024. this._yaw = this._particle.rotation.y;
  59025. this._pitch = this._particle.rotation.x;
  59026. this._roll = this._particle.rotation.z;
  59027. this._quaternionRotationYPR();
  59028. }
  59029. this._quaternionToRotationMatrix();
  59030. }
  59031. if (this._particleHasParent) {
  59032. this._parent = this.particles[this._particle.parentId];
  59033. 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];
  59034. 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];
  59035. 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];
  59036. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59037. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59038. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59039. if (this._computeParticleRotation || this.billboard) {
  59040. 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];
  59041. 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];
  59042. 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];
  59043. 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];
  59044. 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];
  59045. 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];
  59046. 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];
  59047. 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];
  59048. 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];
  59049. }
  59050. }
  59051. else {
  59052. this._particle._globalPosition.x = this._particle.position.x;
  59053. this._particle._globalPosition.y = this._particle.position.y;
  59054. this._particle._globalPosition.z = this._particle.position.z;
  59055. if (this._computeParticleRotation || this.billboard) {
  59056. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59057. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59058. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59059. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59060. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59061. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59062. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59063. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59064. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59065. }
  59066. }
  59067. if (this._particle.translateFromPivot) {
  59068. this._pivotBackTranslation.x = 0.0;
  59069. this._pivotBackTranslation.y = 0.0;
  59070. this._pivotBackTranslation.z = 0.0;
  59071. }
  59072. else {
  59073. this._pivotBackTranslation.x = this._scaledPivot.x;
  59074. this._pivotBackTranslation.y = this._scaledPivot.y;
  59075. this._pivotBackTranslation.z = this._scaledPivot.z;
  59076. }
  59077. // particle vertex loop
  59078. for (pt = 0; pt < this._shape.length; pt++) {
  59079. idx = index + pt * 3;
  59080. colidx = colorIndex + pt * 4;
  59081. uvidx = uvIndex + pt * 2;
  59082. this._vertex.x = this._shape[pt].x;
  59083. this._vertex.y = this._shape[pt].y;
  59084. this._vertex.z = this._shape[pt].z;
  59085. if (this._computeParticleVertex) {
  59086. this.updateParticleVertex(this._particle, this._vertex, pt);
  59087. }
  59088. // positions
  59089. this._vertex.x *= this._particle.scaling.x;
  59090. this._vertex.y *= this._particle.scaling.y;
  59091. this._vertex.z *= this._particle.scaling.z;
  59092. this._vertex.x -= this._scaledPivot.x;
  59093. this._vertex.y -= this._scaledPivot.y;
  59094. this._vertex.z -= this._scaledPivot.z;
  59095. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59096. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59097. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59098. this._rotated.x += this._pivotBackTranslation.x;
  59099. this._rotated.y += this._pivotBackTranslation.y;
  59100. this._rotated.z += this._pivotBackTranslation.z;
  59101. 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;
  59102. 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;
  59103. 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;
  59104. if (this._computeBoundingBox) {
  59105. if (this._positions32[idx] < this._minimum.x) {
  59106. this._minimum.x = this._positions32[idx];
  59107. }
  59108. if (this._positions32[idx] > this._maximum.x) {
  59109. this._maximum.x = this._positions32[idx];
  59110. }
  59111. if (this._positions32[idx + 1] < this._minimum.y) {
  59112. this._minimum.y = this._positions32[idx + 1];
  59113. }
  59114. if (this._positions32[idx + 1] > this._maximum.y) {
  59115. this._maximum.y = this._positions32[idx + 1];
  59116. }
  59117. if (this._positions32[idx + 2] < this._minimum.z) {
  59118. this._minimum.z = this._positions32[idx + 2];
  59119. }
  59120. if (this._positions32[idx + 2] > this._maximum.z) {
  59121. this._maximum.z = this._positions32[idx + 2];
  59122. }
  59123. }
  59124. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59125. if (!this._computeParticleVertex) {
  59126. this._normal.x = this._fixedNormal32[idx];
  59127. this._normal.y = this._fixedNormal32[idx + 1];
  59128. this._normal.z = this._fixedNormal32[idx + 2];
  59129. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59130. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59131. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59132. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59133. 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;
  59134. 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;
  59135. }
  59136. if (this._computeParticleColor && this._particle.color) {
  59137. this._colors32[colidx] = this._particle.color.r;
  59138. this._colors32[colidx + 1] = this._particle.color.g;
  59139. this._colors32[colidx + 2] = this._particle.color.b;
  59140. this._colors32[colidx + 3] = this._particle.color.a;
  59141. }
  59142. if (this._computeParticleTexture) {
  59143. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59144. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59145. }
  59146. }
  59147. }
  59148. // particle just set invisible : scaled to zero and positioned at the origin
  59149. else {
  59150. this._particle._stillInvisible = true; // mark the particle as invisible
  59151. for (pt = 0; pt < this._shape.length; pt++) {
  59152. idx = index + pt * 3;
  59153. colidx = colorIndex + pt * 4;
  59154. uvidx = uvIndex + pt * 2;
  59155. this._positions32[idx] = 0.0;
  59156. this._positions32[idx + 1] = 0.0;
  59157. this._positions32[idx + 2] = 0.0;
  59158. this._normals32[idx] = 0.0;
  59159. this._normals32[idx + 1] = 0.0;
  59160. this._normals32[idx + 2] = 0.0;
  59161. if (this._computeParticleColor && this._particle.color) {
  59162. this._colors32[colidx] = this._particle.color.r;
  59163. this._colors32[colidx + 1] = this._particle.color.g;
  59164. this._colors32[colidx + 2] = this._particle.color.b;
  59165. this._colors32[colidx + 3] = this._particle.color.a;
  59166. }
  59167. if (this._computeParticleTexture) {
  59168. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59169. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59170. }
  59171. }
  59172. }
  59173. // if the particle intersections must be computed : update the bbInfo
  59174. if (this._particlesIntersect) {
  59175. var bInfo = this._particle._boundingInfo;
  59176. var bBox = bInfo.boundingBox;
  59177. var bSphere = bInfo.boundingSphere;
  59178. if (!this._bSphereOnly) {
  59179. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59180. for (var b = 0; b < bBox.vectors.length; b++) {
  59181. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59182. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59183. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59184. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59185. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59186. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59187. 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;
  59188. 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;
  59189. 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;
  59190. }
  59191. bBox._update(this.mesh._worldMatrix);
  59192. }
  59193. // place and scale the particle bouding sphere in the SPS local system, then update it
  59194. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59195. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59196. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59197. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59198. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59199. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59200. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59201. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59202. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59203. 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));
  59204. bSphere._update(this.mesh._worldMatrix);
  59205. }
  59206. // increment indexes for the next particle
  59207. index = idx + 3;
  59208. colorIndex = colidx + 4;
  59209. uvIndex = uvidx + 2;
  59210. }
  59211. // if the VBO must be updated
  59212. if (update) {
  59213. if (this._computeParticleColor) {
  59214. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59215. }
  59216. if (this._computeParticleTexture) {
  59217. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59218. }
  59219. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59220. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59221. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59222. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59223. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59224. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59225. for (var i = 0; i < this._normals32.length; i++) {
  59226. this._fixedNormal32[i] = this._normals32[i];
  59227. }
  59228. }
  59229. if (!this.mesh.areNormalsFrozen) {
  59230. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59231. }
  59232. }
  59233. if (this._depthSort && this._depthSortParticles) {
  59234. this.depthSortedParticles.sort(this._depthSortFunction);
  59235. var dspl = this.depthSortedParticles.length;
  59236. var sorted = 0;
  59237. var lind = 0;
  59238. var sind = 0;
  59239. var sid = 0;
  59240. for (sorted = 0; sorted < dspl; sorted++) {
  59241. lind = this.depthSortedParticles[sorted].indicesLength;
  59242. sind = this.depthSortedParticles[sorted].ind;
  59243. for (var i = 0; i < lind; i++) {
  59244. this._indices32[sid] = this._indices[sind + i];
  59245. sid++;
  59246. }
  59247. }
  59248. this.mesh.updateIndices(this._indices32);
  59249. }
  59250. }
  59251. if (this._computeBoundingBox) {
  59252. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59253. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59254. }
  59255. this.afterUpdateParticles(start, end, update);
  59256. return this;
  59257. };
  59258. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59259. this._halfroll = this._roll * 0.5;
  59260. this._halfpitch = this._pitch * 0.5;
  59261. this._halfyaw = this._yaw * 0.5;
  59262. this._sinRoll = Math.sin(this._halfroll);
  59263. this._cosRoll = Math.cos(this._halfroll);
  59264. this._sinPitch = Math.sin(this._halfpitch);
  59265. this._cosPitch = Math.cos(this._halfpitch);
  59266. this._sinYaw = Math.sin(this._halfyaw);
  59267. this._cosYaw = Math.cos(this._halfyaw);
  59268. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59269. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59270. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59271. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59272. };
  59273. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59274. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59275. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59276. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59277. this._rotMatrix.m[3] = 0;
  59278. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59279. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59280. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59281. this._rotMatrix.m[7] = 0;
  59282. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59283. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59284. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59285. this._rotMatrix.m[11] = 0;
  59286. this._rotMatrix.m[12] = 0;
  59287. this._rotMatrix.m[13] = 0;
  59288. this._rotMatrix.m[14] = 0;
  59289. this._rotMatrix.m[15] = 1.0;
  59290. };
  59291. /**
  59292. * Disposes the SPS.
  59293. */
  59294. SolidParticleSystem.prototype.dispose = function () {
  59295. this.mesh.dispose();
  59296. this.vars = null;
  59297. // drop references to internal big arrays for the GC
  59298. this._positions = null;
  59299. this._indices = null;
  59300. this._normals = null;
  59301. this._uvs = null;
  59302. this._colors = null;
  59303. this._indices32 = null;
  59304. this._positions32 = null;
  59305. this._normals32 = null;
  59306. this._fixedNormal32 = null;
  59307. this._uvs32 = null;
  59308. this._colors32 = null;
  59309. this.pickedParticles = null;
  59310. };
  59311. /**
  59312. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59313. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59314. * @returns the SPS.
  59315. */
  59316. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59317. if (!this._isVisibilityBoxLocked) {
  59318. this.mesh.refreshBoundingInfo();
  59319. }
  59320. return this;
  59321. };
  59322. /**
  59323. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59324. * @param size the size (float) of the visibility box
  59325. * note : this doesn't lock the SPS mesh bounding box.
  59326. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59327. */
  59328. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59329. var vis = size / 2;
  59330. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59331. };
  59332. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59333. /**
  59334. * Gets whether the SPS as always visible or not
  59335. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59336. */
  59337. get: function () {
  59338. return this._alwaysVisible;
  59339. },
  59340. /**
  59341. * Sets the SPS as always visible or not
  59342. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59343. */
  59344. set: function (val) {
  59345. this._alwaysVisible = val;
  59346. this.mesh.alwaysSelectAsActiveMesh = val;
  59347. },
  59348. enumerable: true,
  59349. configurable: true
  59350. });
  59351. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59352. /**
  59353. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59354. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59355. */
  59356. get: function () {
  59357. return this._isVisibilityBoxLocked;
  59358. },
  59359. /**
  59360. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59361. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59362. */
  59363. set: function (val) {
  59364. this._isVisibilityBoxLocked = val;
  59365. var boundingInfo = this.mesh.getBoundingInfo();
  59366. boundingInfo.isLocked = val;
  59367. },
  59368. enumerable: true,
  59369. configurable: true
  59370. });
  59371. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59372. /**
  59373. * Gets if `setParticles()` computes the particle rotations or not.
  59374. * Default value : true. The SPS is faster when it's set to false.
  59375. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59376. */
  59377. get: function () {
  59378. return this._computeParticleRotation;
  59379. },
  59380. /**
  59381. * Tells to `setParticles()` to compute the particle rotations or not.
  59382. * Default value : true. The SPS is faster when it's set to false.
  59383. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59384. */
  59385. set: function (val) {
  59386. this._computeParticleRotation = val;
  59387. },
  59388. enumerable: true,
  59389. configurable: true
  59390. });
  59391. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59392. /**
  59393. * Gets if `setParticles()` computes the particle colors or not.
  59394. * Default value : true. The SPS is faster when it's set to false.
  59395. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59396. */
  59397. get: function () {
  59398. return this._computeParticleColor;
  59399. },
  59400. /**
  59401. * Tells to `setParticles()` to compute the particle colors or not.
  59402. * Default value : true. The SPS is faster when it's set to false.
  59403. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59404. */
  59405. set: function (val) {
  59406. this._computeParticleColor = val;
  59407. },
  59408. enumerable: true,
  59409. configurable: true
  59410. });
  59411. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59412. /**
  59413. * Gets if `setParticles()` computes the particle textures or not.
  59414. * Default value : true. The SPS is faster when it's set to false.
  59415. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59416. */
  59417. get: function () {
  59418. return this._computeParticleTexture;
  59419. },
  59420. set: function (val) {
  59421. this._computeParticleTexture = val;
  59422. },
  59423. enumerable: true,
  59424. configurable: true
  59425. });
  59426. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59427. /**
  59428. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59429. * Default value : false. The SPS is faster when it's set to false.
  59430. * Note : the particle custom vertex positions aren't stored values.
  59431. */
  59432. get: function () {
  59433. return this._computeParticleVertex;
  59434. },
  59435. /**
  59436. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59437. * Default value : false. The SPS is faster when it's set to false.
  59438. * Note : the particle custom vertex positions aren't stored values.
  59439. */
  59440. set: function (val) {
  59441. this._computeParticleVertex = val;
  59442. },
  59443. enumerable: true,
  59444. configurable: true
  59445. });
  59446. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59447. /**
  59448. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59449. */
  59450. get: function () {
  59451. return this._computeBoundingBox;
  59452. },
  59453. /**
  59454. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59455. */
  59456. set: function (val) {
  59457. this._computeBoundingBox = val;
  59458. },
  59459. enumerable: true,
  59460. configurable: true
  59461. });
  59462. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59463. /**
  59464. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59465. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59466. * Default : `true`
  59467. */
  59468. get: function () {
  59469. return this._depthSortParticles;
  59470. },
  59471. /**
  59472. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59473. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59474. * Default : `true`
  59475. */
  59476. set: function (val) {
  59477. this._depthSortParticles = val;
  59478. },
  59479. enumerable: true,
  59480. configurable: true
  59481. });
  59482. // =======================================================================
  59483. // Particle behavior logic
  59484. // these following methods may be overwritten by the user to fit his needs
  59485. /**
  59486. * This function does nothing. It may be overwritten to set all the particle first values.
  59487. * The SPS doesn't call this function, you may have to call it by your own.
  59488. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59489. */
  59490. SolidParticleSystem.prototype.initParticles = function () {
  59491. };
  59492. /**
  59493. * This function does nothing. It may be overwritten to recycle a particle.
  59494. * The SPS doesn't call this function, you may have to call it by your own.
  59495. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59496. * @param particle The particle to recycle
  59497. * @returns the recycled particle
  59498. */
  59499. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59500. return particle;
  59501. };
  59502. /**
  59503. * Updates a particle : this function should be overwritten by the user.
  59504. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59505. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59506. * @example : just set a particle position or velocity and recycle conditions
  59507. * @param particle The particle to update
  59508. * @returns the updated particle
  59509. */
  59510. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59511. return particle;
  59512. };
  59513. /**
  59514. * Updates a vertex of a particle : it can be overwritten by the user.
  59515. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59516. * @param particle the current particle
  59517. * @param vertex the current index of the current particle
  59518. * @param pt the index of the current vertex in the particle shape
  59519. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59520. * @example : just set a vertex particle position
  59521. * @returns the updated vertex
  59522. */
  59523. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59524. return vertex;
  59525. };
  59526. /**
  59527. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59528. * This does nothing and may be overwritten by the user.
  59529. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59530. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59531. * @param update the boolean update value actually passed to setParticles()
  59532. */
  59533. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59534. };
  59535. /**
  59536. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59537. * This will be passed three parameters.
  59538. * This does nothing and may be overwritten by the user.
  59539. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59540. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59541. * @param update the boolean update value actually passed to setParticles()
  59542. */
  59543. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59544. };
  59545. return SolidParticleSystem;
  59546. }());
  59547. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59548. })(BABYLON || (BABYLON = {}));
  59549. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59550. var BABYLON;
  59551. (function (BABYLON) {
  59552. var ShaderMaterial = /** @class */ (function (_super) {
  59553. __extends(ShaderMaterial, _super);
  59554. function ShaderMaterial(name, scene, shaderPath, options) {
  59555. var _this = _super.call(this, name, scene) || this;
  59556. _this._textures = {};
  59557. _this._textureArrays = {};
  59558. _this._floats = {};
  59559. _this._ints = {};
  59560. _this._floatsArrays = {};
  59561. _this._colors3 = {};
  59562. _this._colors3Arrays = {};
  59563. _this._colors4 = {};
  59564. _this._vectors2 = {};
  59565. _this._vectors3 = {};
  59566. _this._vectors4 = {};
  59567. _this._matrices = {};
  59568. _this._matrices3x3 = {};
  59569. _this._matrices2x2 = {};
  59570. _this._vectors2Arrays = {};
  59571. _this._vectors3Arrays = {};
  59572. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59573. _this._shaderPath = shaderPath;
  59574. options.needAlphaBlending = options.needAlphaBlending || false;
  59575. options.needAlphaTesting = options.needAlphaTesting || false;
  59576. options.attributes = options.attributes || ["position", "normal", "uv"];
  59577. options.uniforms = options.uniforms || ["worldViewProjection"];
  59578. options.uniformBuffers = options.uniformBuffers || [];
  59579. options.samplers = options.samplers || [];
  59580. options.defines = options.defines || [];
  59581. _this._options = options;
  59582. return _this;
  59583. }
  59584. ShaderMaterial.prototype.getClassName = function () {
  59585. return "ShaderMaterial";
  59586. };
  59587. ShaderMaterial.prototype.needAlphaBlending = function () {
  59588. return this._options.needAlphaBlending;
  59589. };
  59590. ShaderMaterial.prototype.needAlphaTesting = function () {
  59591. return this._options.needAlphaTesting;
  59592. };
  59593. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59594. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59595. this._options.uniforms.push(uniformName);
  59596. }
  59597. };
  59598. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59599. if (this._options.samplers.indexOf(name) === -1) {
  59600. this._options.samplers.push(name);
  59601. }
  59602. this._textures[name] = texture;
  59603. return this;
  59604. };
  59605. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59606. if (this._options.samplers.indexOf(name) === -1) {
  59607. this._options.samplers.push(name);
  59608. }
  59609. this._checkUniform(name);
  59610. this._textureArrays[name] = textures;
  59611. return this;
  59612. };
  59613. ShaderMaterial.prototype.setFloat = function (name, value) {
  59614. this._checkUniform(name);
  59615. this._floats[name] = value;
  59616. return this;
  59617. };
  59618. ShaderMaterial.prototype.setInt = function (name, value) {
  59619. this._checkUniform(name);
  59620. this._ints[name] = value;
  59621. return this;
  59622. };
  59623. ShaderMaterial.prototype.setFloats = function (name, value) {
  59624. this._checkUniform(name);
  59625. this._floatsArrays[name] = value;
  59626. return this;
  59627. };
  59628. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59629. this._checkUniform(name);
  59630. this._colors3[name] = value;
  59631. return this;
  59632. };
  59633. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59634. this._checkUniform(name);
  59635. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59636. color.toArray(arr, arr.length);
  59637. return arr;
  59638. }, []);
  59639. return this;
  59640. };
  59641. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59642. this._checkUniform(name);
  59643. this._colors4[name] = value;
  59644. return this;
  59645. };
  59646. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59647. this._checkUniform(name);
  59648. this._vectors2[name] = value;
  59649. return this;
  59650. };
  59651. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59652. this._checkUniform(name);
  59653. this._vectors3[name] = value;
  59654. return this;
  59655. };
  59656. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59657. this._checkUniform(name);
  59658. this._vectors4[name] = value;
  59659. return this;
  59660. };
  59661. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59662. this._checkUniform(name);
  59663. this._matrices[name] = value;
  59664. return this;
  59665. };
  59666. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59667. this._checkUniform(name);
  59668. this._matrices3x3[name] = value;
  59669. return this;
  59670. };
  59671. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59672. this._checkUniform(name);
  59673. this._matrices2x2[name] = value;
  59674. return this;
  59675. };
  59676. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59677. this._checkUniform(name);
  59678. this._vectors2Arrays[name] = value;
  59679. return this;
  59680. };
  59681. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59682. this._checkUniform(name);
  59683. this._vectors3Arrays[name] = value;
  59684. return this;
  59685. };
  59686. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59687. if (!mesh) {
  59688. return true;
  59689. }
  59690. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59691. return false;
  59692. }
  59693. return false;
  59694. };
  59695. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59696. var scene = this.getScene();
  59697. var engine = scene.getEngine();
  59698. if (!this.checkReadyOnEveryCall) {
  59699. if (this._renderId === scene.getRenderId()) {
  59700. if (this._checkCache(scene, mesh, useInstances)) {
  59701. return true;
  59702. }
  59703. }
  59704. }
  59705. // Instances
  59706. var defines = [];
  59707. var attribs = [];
  59708. var fallbacks = new BABYLON.EffectFallbacks();
  59709. if (useInstances) {
  59710. defines.push("#define INSTANCES");
  59711. }
  59712. for (var index = 0; index < this._options.defines.length; index++) {
  59713. defines.push(this._options.defines[index]);
  59714. }
  59715. for (var index = 0; index < this._options.attributes.length; index++) {
  59716. attribs.push(this._options.attributes[index]);
  59717. }
  59718. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59719. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59720. defines.push("#define VERTEXCOLOR");
  59721. }
  59722. // Bones
  59723. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59724. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59725. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59726. if (mesh.numBoneInfluencers > 4) {
  59727. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59728. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59729. }
  59730. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59731. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59732. fallbacks.addCPUSkinningFallback(0, mesh);
  59733. if (this._options.uniforms.indexOf("mBones") === -1) {
  59734. this._options.uniforms.push("mBones");
  59735. }
  59736. }
  59737. else {
  59738. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59739. }
  59740. // Textures
  59741. for (var name in this._textures) {
  59742. if (!this._textures[name].isReady()) {
  59743. return false;
  59744. }
  59745. }
  59746. // Alpha test
  59747. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59748. defines.push("#define ALPHATEST");
  59749. }
  59750. var previousEffect = this._effect;
  59751. var join = defines.join("\n");
  59752. this._effect = engine.createEffect(this._shaderPath, {
  59753. attributes: attribs,
  59754. uniformsNames: this._options.uniforms,
  59755. uniformBuffersNames: this._options.uniformBuffers,
  59756. samplers: this._options.samplers,
  59757. defines: join,
  59758. fallbacks: fallbacks,
  59759. onCompiled: this.onCompiled,
  59760. onError: this.onError
  59761. }, engine);
  59762. if (!this._effect.isReady()) {
  59763. return false;
  59764. }
  59765. if (previousEffect !== this._effect) {
  59766. scene.resetCachedMaterial();
  59767. }
  59768. this._renderId = scene.getRenderId();
  59769. return true;
  59770. };
  59771. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59772. var scene = this.getScene();
  59773. if (!this._effect) {
  59774. return;
  59775. }
  59776. if (this._options.uniforms.indexOf("world") !== -1) {
  59777. this._effect.setMatrix("world", world);
  59778. }
  59779. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59780. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59781. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59782. }
  59783. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59784. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59785. }
  59786. };
  59787. ShaderMaterial.prototype.bind = function (world, mesh) {
  59788. // Std values
  59789. this.bindOnlyWorldMatrix(world);
  59790. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59791. if (this._options.uniforms.indexOf("view") !== -1) {
  59792. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59793. }
  59794. if (this._options.uniforms.indexOf("projection") !== -1) {
  59795. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59796. }
  59797. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59798. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59799. }
  59800. // Bones
  59801. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59802. var name;
  59803. // Texture
  59804. for (name in this._textures) {
  59805. this._effect.setTexture(name, this._textures[name]);
  59806. }
  59807. // Texture arrays
  59808. for (name in this._textureArrays) {
  59809. this._effect.setTextureArray(name, this._textureArrays[name]);
  59810. }
  59811. // Int
  59812. for (name in this._ints) {
  59813. this._effect.setInt(name, this._ints[name]);
  59814. }
  59815. // Float
  59816. for (name in this._floats) {
  59817. this._effect.setFloat(name, this._floats[name]);
  59818. }
  59819. // Floats
  59820. for (name in this._floatsArrays) {
  59821. this._effect.setArray(name, this._floatsArrays[name]);
  59822. }
  59823. // Color3
  59824. for (name in this._colors3) {
  59825. this._effect.setColor3(name, this._colors3[name]);
  59826. }
  59827. for (name in this._colors3Arrays) {
  59828. this._effect.setArray3(name, this._colors3Arrays[name]);
  59829. }
  59830. // Color4
  59831. for (name in this._colors4) {
  59832. var color = this._colors4[name];
  59833. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59834. }
  59835. // Vector2
  59836. for (name in this._vectors2) {
  59837. this._effect.setVector2(name, this._vectors2[name]);
  59838. }
  59839. // Vector3
  59840. for (name in this._vectors3) {
  59841. this._effect.setVector3(name, this._vectors3[name]);
  59842. }
  59843. // Vector4
  59844. for (name in this._vectors4) {
  59845. this._effect.setVector4(name, this._vectors4[name]);
  59846. }
  59847. // Matrix
  59848. for (name in this._matrices) {
  59849. this._effect.setMatrix(name, this._matrices[name]);
  59850. }
  59851. // Matrix 3x3
  59852. for (name in this._matrices3x3) {
  59853. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59854. }
  59855. // Matrix 2x2
  59856. for (name in this._matrices2x2) {
  59857. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59858. }
  59859. // Vector2Array
  59860. for (name in this._vectors2Arrays) {
  59861. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59862. }
  59863. // Vector3Array
  59864. for (name in this._vectors3Arrays) {
  59865. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59866. }
  59867. }
  59868. this._afterBind(mesh);
  59869. };
  59870. ShaderMaterial.prototype.getActiveTextures = function () {
  59871. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59872. for (var name in this._textures) {
  59873. activeTextures.push(this._textures[name]);
  59874. }
  59875. for (var name in this._textureArrays) {
  59876. var array = this._textureArrays[name];
  59877. for (var index = 0; index < array.length; index++) {
  59878. activeTextures.push(array[index]);
  59879. }
  59880. }
  59881. return activeTextures;
  59882. };
  59883. ShaderMaterial.prototype.hasTexture = function (texture) {
  59884. if (_super.prototype.hasTexture.call(this, texture)) {
  59885. return true;
  59886. }
  59887. for (var name in this._textures) {
  59888. if (this._textures[name] === texture) {
  59889. return true;
  59890. }
  59891. }
  59892. for (var name in this._textureArrays) {
  59893. var array = this._textureArrays[name];
  59894. for (var index = 0; index < array.length; index++) {
  59895. if (array[index] === texture) {
  59896. return true;
  59897. }
  59898. }
  59899. }
  59900. return false;
  59901. };
  59902. ShaderMaterial.prototype.clone = function (name) {
  59903. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59904. return newShaderMaterial;
  59905. };
  59906. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59907. if (forceDisposeTextures) {
  59908. var name;
  59909. for (name in this._textures) {
  59910. this._textures[name].dispose();
  59911. }
  59912. for (name in this._textureArrays) {
  59913. var array = this._textureArrays[name];
  59914. for (var index = 0; index < array.length; index++) {
  59915. array[index].dispose();
  59916. }
  59917. }
  59918. }
  59919. this._textures = {};
  59920. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59921. };
  59922. ShaderMaterial.prototype.serialize = function () {
  59923. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59924. serializationObject.customType = "BABYLON.ShaderMaterial";
  59925. serializationObject.options = this._options;
  59926. serializationObject.shaderPath = this._shaderPath;
  59927. var name;
  59928. // Texture
  59929. serializationObject.textures = {};
  59930. for (name in this._textures) {
  59931. serializationObject.textures[name] = this._textures[name].serialize();
  59932. }
  59933. // Texture arrays
  59934. serializationObject.textureArrays = {};
  59935. for (name in this._textureArrays) {
  59936. serializationObject.textureArrays[name] = [];
  59937. var array = this._textureArrays[name];
  59938. for (var index = 0; index < array.length; index++) {
  59939. serializationObject.textureArrays[name].push(array[index].serialize());
  59940. }
  59941. }
  59942. // Float
  59943. serializationObject.floats = {};
  59944. for (name in this._floats) {
  59945. serializationObject.floats[name] = this._floats[name];
  59946. }
  59947. // Float s
  59948. serializationObject.FloatArrays = {};
  59949. for (name in this._floatsArrays) {
  59950. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59951. }
  59952. // Color3
  59953. serializationObject.colors3 = {};
  59954. for (name in this._colors3) {
  59955. serializationObject.colors3[name] = this._colors3[name].asArray();
  59956. }
  59957. // Color3 array
  59958. serializationObject.colors3Arrays = {};
  59959. for (name in this._colors3Arrays) {
  59960. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59961. }
  59962. // Color4
  59963. serializationObject.colors4 = {};
  59964. for (name in this._colors4) {
  59965. serializationObject.colors4[name] = this._colors4[name].asArray();
  59966. }
  59967. // Vector2
  59968. serializationObject.vectors2 = {};
  59969. for (name in this._vectors2) {
  59970. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59971. }
  59972. // Vector3
  59973. serializationObject.vectors3 = {};
  59974. for (name in this._vectors3) {
  59975. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59976. }
  59977. // Vector4
  59978. serializationObject.vectors4 = {};
  59979. for (name in this._vectors4) {
  59980. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59981. }
  59982. // Matrix
  59983. serializationObject.matrices = {};
  59984. for (name in this._matrices) {
  59985. serializationObject.matrices[name] = this._matrices[name].asArray();
  59986. }
  59987. // Matrix 3x3
  59988. serializationObject.matrices3x3 = {};
  59989. for (name in this._matrices3x3) {
  59990. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59991. }
  59992. // Matrix 2x2
  59993. serializationObject.matrices2x2 = {};
  59994. for (name in this._matrices2x2) {
  59995. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59996. }
  59997. // Vector2Array
  59998. serializationObject.vectors2Arrays = {};
  59999. for (name in this._vectors2Arrays) {
  60000. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60001. }
  60002. // Vector3Array
  60003. serializationObject.vectors3Arrays = {};
  60004. for (name in this._vectors3Arrays) {
  60005. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60006. }
  60007. return serializationObject;
  60008. };
  60009. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60010. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60011. var name;
  60012. // Texture
  60013. for (name in source.textures) {
  60014. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60015. }
  60016. // Texture arrays
  60017. for (name in source.textureArrays) {
  60018. var array = source.textureArrays[name];
  60019. var textureArray = new Array();
  60020. for (var index = 0; index < array.length; index++) {
  60021. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60022. }
  60023. material.setTextureArray(name, textureArray);
  60024. }
  60025. // Float
  60026. for (name in source.floats) {
  60027. material.setFloat(name, source.floats[name]);
  60028. }
  60029. // Float s
  60030. for (name in source.floatsArrays) {
  60031. material.setFloats(name, source.floatsArrays[name]);
  60032. }
  60033. // Color3
  60034. for (name in source.colors3) {
  60035. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60036. }
  60037. // Color3 arrays
  60038. for (name in source.colors3Arrays) {
  60039. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60040. if (i % 3 === 0) {
  60041. arr.push([num]);
  60042. }
  60043. else {
  60044. arr[arr.length - 1].push(num);
  60045. }
  60046. return arr;
  60047. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60048. material.setColor3Array(name, colors);
  60049. }
  60050. // Color4
  60051. for (name in source.colors4) {
  60052. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60053. }
  60054. // Vector2
  60055. for (name in source.vectors2) {
  60056. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60057. }
  60058. // Vector3
  60059. for (name in source.vectors3) {
  60060. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60061. }
  60062. // Vector4
  60063. for (name in source.vectors4) {
  60064. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60065. }
  60066. // Matrix
  60067. for (name in source.matrices) {
  60068. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60069. }
  60070. // Matrix 3x3
  60071. for (name in source.matrices3x3) {
  60072. material.setMatrix3x3(name, source.matrices3x3[name]);
  60073. }
  60074. // Matrix 2x2
  60075. for (name in source.matrices2x2) {
  60076. material.setMatrix2x2(name, source.matrices2x2[name]);
  60077. }
  60078. // Vector2Array
  60079. for (name in source.vectors2Arrays) {
  60080. material.setArray2(name, source.vectors2Arrays[name]);
  60081. }
  60082. // Vector3Array
  60083. for (name in source.vectors3Arrays) {
  60084. material.setArray3(name, source.vectors3Arrays[name]);
  60085. }
  60086. return material;
  60087. };
  60088. return ShaderMaterial;
  60089. }(BABYLON.Material));
  60090. BABYLON.ShaderMaterial = ShaderMaterial;
  60091. })(BABYLON || (BABYLON = {}));
  60092. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60093. var BABYLON;
  60094. (function (BABYLON) {
  60095. var GroundMesh = /** @class */ (function (_super) {
  60096. __extends(GroundMesh, _super);
  60097. function GroundMesh(name, scene) {
  60098. var _this = _super.call(this, name, scene) || this;
  60099. _this.generateOctree = false;
  60100. return _this;
  60101. }
  60102. GroundMesh.prototype.getClassName = function () {
  60103. return "GroundMesh";
  60104. };
  60105. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60106. get: function () {
  60107. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60108. },
  60109. enumerable: true,
  60110. configurable: true
  60111. });
  60112. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60113. get: function () {
  60114. return this._subdivisionsX;
  60115. },
  60116. enumerable: true,
  60117. configurable: true
  60118. });
  60119. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60120. get: function () {
  60121. return this._subdivisionsY;
  60122. },
  60123. enumerable: true,
  60124. configurable: true
  60125. });
  60126. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60127. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60128. this._subdivisionsX = chunksCount;
  60129. this._subdivisionsY = chunksCount;
  60130. this.subdivide(chunksCount);
  60131. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60132. };
  60133. /**
  60134. * Returns a height (y) value in the Worl system :
  60135. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60136. * Returns the ground y position if (x, z) are outside the ground surface.
  60137. */
  60138. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60139. var world = this.getWorldMatrix();
  60140. var invMat = BABYLON.Tmp.Matrix[5];
  60141. world.invertToRef(invMat);
  60142. var tmpVect = BABYLON.Tmp.Vector3[8];
  60143. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60144. x = tmpVect.x;
  60145. z = tmpVect.z;
  60146. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60147. return this.position.y;
  60148. }
  60149. if (!this._heightQuads || this._heightQuads.length == 0) {
  60150. this._initHeightQuads();
  60151. this._computeHeightQuads();
  60152. }
  60153. var facet = this._getFacetAt(x, z);
  60154. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60155. // return y in the World system
  60156. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60157. return tmpVect.y;
  60158. };
  60159. /**
  60160. * Returns a normalized vector (Vector3) orthogonal to the ground
  60161. * at the ground coordinates (x, z) expressed in the World system.
  60162. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60163. */
  60164. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60165. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60166. this.getNormalAtCoordinatesToRef(x, z, normal);
  60167. return normal;
  60168. };
  60169. /**
  60170. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60171. * at the ground coordinates (x, z) expressed in the World system.
  60172. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60173. * Returns the GroundMesh.
  60174. */
  60175. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60176. var world = this.getWorldMatrix();
  60177. var tmpMat = BABYLON.Tmp.Matrix[5];
  60178. world.invertToRef(tmpMat);
  60179. var tmpVect = BABYLON.Tmp.Vector3[8];
  60180. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60181. x = tmpVect.x;
  60182. z = tmpVect.z;
  60183. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60184. return this;
  60185. }
  60186. if (!this._heightQuads || this._heightQuads.length == 0) {
  60187. this._initHeightQuads();
  60188. this._computeHeightQuads();
  60189. }
  60190. var facet = this._getFacetAt(x, z);
  60191. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60192. return this;
  60193. };
  60194. /**
  60195. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60196. * if the ground has been updated.
  60197. * This can be used in the render loop.
  60198. * Returns the GroundMesh.
  60199. */
  60200. GroundMesh.prototype.updateCoordinateHeights = function () {
  60201. if (!this._heightQuads || this._heightQuads.length == 0) {
  60202. this._initHeightQuads();
  60203. }
  60204. this._computeHeightQuads();
  60205. return this;
  60206. };
  60207. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60208. GroundMesh.prototype._getFacetAt = function (x, z) {
  60209. // retrieve col and row from x, z coordinates in the ground local system
  60210. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60211. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60212. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60213. var facet;
  60214. if (z < quad.slope.x * x + quad.slope.y) {
  60215. facet = quad.facet1;
  60216. }
  60217. else {
  60218. facet = quad.facet2;
  60219. }
  60220. return facet;
  60221. };
  60222. // Creates and populates the heightMap array with "facet" elements :
  60223. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60224. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60225. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60226. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60227. // Returns the GroundMesh.
  60228. GroundMesh.prototype._initHeightQuads = function () {
  60229. var subdivisionsX = this._subdivisionsX;
  60230. var subdivisionsY = this._subdivisionsY;
  60231. this._heightQuads = new Array();
  60232. for (var row = 0; row < subdivisionsY; row++) {
  60233. for (var col = 0; col < subdivisionsX; col++) {
  60234. 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) };
  60235. this._heightQuads[row * subdivisionsX + col] = quad;
  60236. }
  60237. }
  60238. return this;
  60239. };
  60240. // Compute each quad element values and update the the heightMap array :
  60241. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60242. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60243. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60244. // Returns the GroundMesh.
  60245. GroundMesh.prototype._computeHeightQuads = function () {
  60246. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60247. if (!positions) {
  60248. return this;
  60249. }
  60250. var v1 = BABYLON.Tmp.Vector3[3];
  60251. var v2 = BABYLON.Tmp.Vector3[2];
  60252. var v3 = BABYLON.Tmp.Vector3[1];
  60253. var v4 = BABYLON.Tmp.Vector3[0];
  60254. var v1v2 = BABYLON.Tmp.Vector3[4];
  60255. var v1v3 = BABYLON.Tmp.Vector3[5];
  60256. var v1v4 = BABYLON.Tmp.Vector3[6];
  60257. var norm1 = BABYLON.Tmp.Vector3[7];
  60258. var norm2 = BABYLON.Tmp.Vector3[8];
  60259. var i = 0;
  60260. var j = 0;
  60261. var k = 0;
  60262. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60263. var h = 0;
  60264. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60265. var d2 = 0;
  60266. var subdivisionsX = this._subdivisionsX;
  60267. var subdivisionsY = this._subdivisionsY;
  60268. for (var row = 0; row < subdivisionsY; row++) {
  60269. for (var col = 0; col < subdivisionsX; col++) {
  60270. i = col * 3;
  60271. j = row * (subdivisionsX + 1) * 3;
  60272. k = (row + 1) * (subdivisionsX + 1) * 3;
  60273. v1.x = positions[j + i];
  60274. v1.y = positions[j + i + 1];
  60275. v1.z = positions[j + i + 2];
  60276. v2.x = positions[j + i + 3];
  60277. v2.y = positions[j + i + 4];
  60278. v2.z = positions[j + i + 5];
  60279. v3.x = positions[k + i];
  60280. v3.y = positions[k + i + 1];
  60281. v3.z = positions[k + i + 2];
  60282. v4.x = positions[k + i + 3];
  60283. v4.y = positions[k + i + 4];
  60284. v4.z = positions[k + i + 5];
  60285. // 2D slope V1V4
  60286. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60287. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60288. // facet equations :
  60289. // we compute each facet normal vector
  60290. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60291. // we compute the value d by applying the equation to v1 which belongs to the plane
  60292. // then we store the facet equation in a Vector4
  60293. v2.subtractToRef(v1, v1v2);
  60294. v3.subtractToRef(v1, v1v3);
  60295. v4.subtractToRef(v1, v1v4);
  60296. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60297. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60298. norm1.normalize();
  60299. norm2.normalize();
  60300. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60301. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60302. var quad = this._heightQuads[row * subdivisionsX + col];
  60303. quad.slope.copyFromFloats(cd, h);
  60304. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60305. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60306. }
  60307. }
  60308. return this;
  60309. };
  60310. GroundMesh.prototype.serialize = function (serializationObject) {
  60311. _super.prototype.serialize.call(this, serializationObject);
  60312. serializationObject.subdivisionsX = this._subdivisionsX;
  60313. serializationObject.subdivisionsY = this._subdivisionsY;
  60314. serializationObject.minX = this._minX;
  60315. serializationObject.maxX = this._maxX;
  60316. serializationObject.minZ = this._minZ;
  60317. serializationObject.maxZ = this._maxZ;
  60318. serializationObject.width = this._width;
  60319. serializationObject.height = this._height;
  60320. };
  60321. GroundMesh.Parse = function (parsedMesh, scene) {
  60322. var result = new GroundMesh(parsedMesh.name, scene);
  60323. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60324. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60325. result._minX = parsedMesh.minX;
  60326. result._maxX = parsedMesh.maxX;
  60327. result._minZ = parsedMesh.minZ;
  60328. result._maxZ = parsedMesh.maxZ;
  60329. result._width = parsedMesh.width;
  60330. result._height = parsedMesh.height;
  60331. return result;
  60332. };
  60333. return GroundMesh;
  60334. }(BABYLON.Mesh));
  60335. BABYLON.GroundMesh = GroundMesh;
  60336. })(BABYLON || (BABYLON = {}));
  60337. //# sourceMappingURL=babylon.groundMesh.js.map
  60338. var BABYLON;
  60339. (function (BABYLON) {
  60340. /**
  60341. * Creates an instance based on a source mesh.
  60342. */
  60343. var InstancedMesh = /** @class */ (function (_super) {
  60344. __extends(InstancedMesh, _super);
  60345. function InstancedMesh(name, source) {
  60346. var _this = _super.call(this, name, source.getScene()) || this;
  60347. source.instances.push(_this);
  60348. _this._sourceMesh = source;
  60349. _this.position.copyFrom(source.position);
  60350. _this.rotation.copyFrom(source.rotation);
  60351. _this.scaling.copyFrom(source.scaling);
  60352. if (source.rotationQuaternion) {
  60353. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60354. }
  60355. _this.infiniteDistance = source.infiniteDistance;
  60356. _this.setPivotMatrix(source.getPivotMatrix());
  60357. _this.refreshBoundingInfo();
  60358. _this._syncSubMeshes();
  60359. return _this;
  60360. }
  60361. /**
  60362. * Returns the string "InstancedMesh".
  60363. */
  60364. InstancedMesh.prototype.getClassName = function () {
  60365. return "InstancedMesh";
  60366. };
  60367. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60368. // Methods
  60369. get: function () {
  60370. return this._sourceMesh.receiveShadows;
  60371. },
  60372. enumerable: true,
  60373. configurable: true
  60374. });
  60375. Object.defineProperty(InstancedMesh.prototype, "material", {
  60376. get: function () {
  60377. return this._sourceMesh.material;
  60378. },
  60379. enumerable: true,
  60380. configurable: true
  60381. });
  60382. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60383. get: function () {
  60384. return this._sourceMesh.visibility;
  60385. },
  60386. enumerable: true,
  60387. configurable: true
  60388. });
  60389. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60390. get: function () {
  60391. return this._sourceMesh.skeleton;
  60392. },
  60393. enumerable: true,
  60394. configurable: true
  60395. });
  60396. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60397. get: function () {
  60398. return this._sourceMesh.renderingGroupId;
  60399. },
  60400. set: function (value) {
  60401. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60402. return;
  60403. }
  60404. //no-op with warning
  60405. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60406. },
  60407. enumerable: true,
  60408. configurable: true
  60409. });
  60410. /**
  60411. * Returns the total number of vertices (integer).
  60412. */
  60413. InstancedMesh.prototype.getTotalVertices = function () {
  60414. return this._sourceMesh.getTotalVertices();
  60415. };
  60416. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60417. get: function () {
  60418. return this._sourceMesh;
  60419. },
  60420. enumerable: true,
  60421. configurable: true
  60422. });
  60423. /**
  60424. * Is this node ready to be used/rendered
  60425. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60426. * @return {boolean} is it ready
  60427. */
  60428. InstancedMesh.prototype.isReady = function (completeCheck) {
  60429. if (completeCheck === void 0) { completeCheck = false; }
  60430. return this._sourceMesh.isReady(completeCheck, true);
  60431. };
  60432. /**
  60433. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60434. */
  60435. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60436. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60437. };
  60438. /**
  60439. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60440. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60441. * The `data` are either a numeric array either a Float32Array.
  60442. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60443. * 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).
  60444. * Note that a new underlying VertexBuffer object is created each call.
  60445. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60446. *
  60447. * Possible `kind` values :
  60448. * - BABYLON.VertexBuffer.PositionKind
  60449. * - BABYLON.VertexBuffer.UVKind
  60450. * - BABYLON.VertexBuffer.UV2Kind
  60451. * - BABYLON.VertexBuffer.UV3Kind
  60452. * - BABYLON.VertexBuffer.UV4Kind
  60453. * - BABYLON.VertexBuffer.UV5Kind
  60454. * - BABYLON.VertexBuffer.UV6Kind
  60455. * - BABYLON.VertexBuffer.ColorKind
  60456. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60457. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60458. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60459. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60460. *
  60461. * Returns the Mesh.
  60462. */
  60463. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60464. if (this.sourceMesh) {
  60465. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60466. }
  60467. return this.sourceMesh;
  60468. };
  60469. /**
  60470. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60471. * If the mesh has no geometry, it is simply returned as it is.
  60472. * The `data` are either a numeric array either a Float32Array.
  60473. * No new underlying VertexBuffer object is created.
  60474. * 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.
  60475. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60476. *
  60477. * Possible `kind` values :
  60478. * - BABYLON.VertexBuffer.PositionKind
  60479. * - BABYLON.VertexBuffer.UVKind
  60480. * - BABYLON.VertexBuffer.UV2Kind
  60481. * - BABYLON.VertexBuffer.UV3Kind
  60482. * - BABYLON.VertexBuffer.UV4Kind
  60483. * - BABYLON.VertexBuffer.UV5Kind
  60484. * - BABYLON.VertexBuffer.UV6Kind
  60485. * - BABYLON.VertexBuffer.ColorKind
  60486. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60487. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60488. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60489. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60490. *
  60491. * Returns the Mesh.
  60492. */
  60493. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60494. if (this.sourceMesh) {
  60495. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60496. }
  60497. return this.sourceMesh;
  60498. };
  60499. /**
  60500. * Sets the mesh indices.
  60501. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60502. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60503. * This method creates a new index buffer each call.
  60504. * Returns the Mesh.
  60505. */
  60506. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60507. if (totalVertices === void 0) { totalVertices = null; }
  60508. if (this.sourceMesh) {
  60509. this.sourceMesh.setIndices(indices, totalVertices);
  60510. }
  60511. return this.sourceMesh;
  60512. };
  60513. /**
  60514. * Boolean : True if the mesh owns the requested kind of data.
  60515. */
  60516. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60517. return this._sourceMesh.isVerticesDataPresent(kind);
  60518. };
  60519. /**
  60520. * Returns an array of indices (IndicesArray).
  60521. */
  60522. InstancedMesh.prototype.getIndices = function () {
  60523. return this._sourceMesh.getIndices();
  60524. };
  60525. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60526. get: function () {
  60527. return this._sourceMesh._positions;
  60528. },
  60529. enumerable: true,
  60530. configurable: true
  60531. });
  60532. /**
  60533. * Sets a new updated BoundingInfo to the mesh.
  60534. * Returns the mesh.
  60535. */
  60536. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60537. var meshBB = this._sourceMesh.getBoundingInfo();
  60538. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60539. this._updateBoundingInfo();
  60540. return this;
  60541. };
  60542. InstancedMesh.prototype._preActivate = function () {
  60543. if (this._currentLOD) {
  60544. this._currentLOD._preActivate();
  60545. }
  60546. return this;
  60547. };
  60548. InstancedMesh.prototype._activate = function (renderId) {
  60549. if (this._currentLOD) {
  60550. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60551. }
  60552. return this;
  60553. };
  60554. /**
  60555. * Returns the current associated LOD AbstractMesh.
  60556. */
  60557. InstancedMesh.prototype.getLOD = function (camera) {
  60558. if (!camera) {
  60559. return this;
  60560. }
  60561. var boundingInfo = this.getBoundingInfo();
  60562. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60563. if (this._currentLOD === this.sourceMesh) {
  60564. return this;
  60565. }
  60566. return this._currentLOD;
  60567. };
  60568. InstancedMesh.prototype._syncSubMeshes = function () {
  60569. this.releaseSubMeshes();
  60570. if (this._sourceMesh.subMeshes) {
  60571. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60572. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60573. }
  60574. }
  60575. return this;
  60576. };
  60577. InstancedMesh.prototype._generatePointsArray = function () {
  60578. return this._sourceMesh._generatePointsArray();
  60579. };
  60580. /**
  60581. * Creates a new InstancedMesh from the current mesh.
  60582. * - name (string) : the cloned mesh name
  60583. * - newParent (optional Node) : the optional Node to parent the clone to.
  60584. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60585. *
  60586. * Returns the clone.
  60587. */
  60588. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60589. var result = this._sourceMesh.createInstance(name);
  60590. // Deep copy
  60591. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60592. // Bounding info
  60593. this.refreshBoundingInfo();
  60594. // Parent
  60595. if (newParent) {
  60596. result.parent = newParent;
  60597. }
  60598. if (!doNotCloneChildren) {
  60599. // Children
  60600. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60601. var mesh = this.getScene().meshes[index];
  60602. if (mesh.parent === this) {
  60603. mesh.clone(mesh.name, result);
  60604. }
  60605. }
  60606. }
  60607. result.computeWorldMatrix(true);
  60608. return result;
  60609. };
  60610. /**
  60611. * Disposes the InstancedMesh.
  60612. * Returns nothing.
  60613. */
  60614. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60615. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60616. // Remove from mesh
  60617. var index = this._sourceMesh.instances.indexOf(this);
  60618. this._sourceMesh.instances.splice(index, 1);
  60619. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60620. };
  60621. return InstancedMesh;
  60622. }(BABYLON.AbstractMesh));
  60623. BABYLON.InstancedMesh = InstancedMesh;
  60624. })(BABYLON || (BABYLON = {}));
  60625. //# sourceMappingURL=babylon.instancedMesh.js.map
  60626. var BABYLON;
  60627. (function (BABYLON) {
  60628. var LinesMesh = /** @class */ (function (_super) {
  60629. __extends(LinesMesh, _super);
  60630. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60631. if (scene === void 0) { scene = null; }
  60632. if (parent === void 0) { parent = null; }
  60633. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60634. _this.useVertexColor = useVertexColor;
  60635. _this.useVertexAlpha = useVertexAlpha;
  60636. _this.color = new BABYLON.Color3(1, 1, 1);
  60637. _this.alpha = 1;
  60638. if (source) {
  60639. _this.color = source.color.clone();
  60640. _this.alpha = source.alpha;
  60641. _this.useVertexColor = source.useVertexColor;
  60642. _this.useVertexAlpha = source.useVertexAlpha;
  60643. }
  60644. _this._intersectionThreshold = 0.1;
  60645. var defines = [];
  60646. var options = {
  60647. attributes: [BABYLON.VertexBuffer.PositionKind],
  60648. uniforms: ["world", "viewProjection"],
  60649. needAlphaBlending: true,
  60650. defines: defines
  60651. };
  60652. if (useVertexAlpha === false) {
  60653. options.needAlphaBlending = false;
  60654. }
  60655. if (!useVertexColor) {
  60656. options.uniforms.push("color");
  60657. }
  60658. else {
  60659. options.defines.push("#define VERTEXCOLOR");
  60660. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60661. }
  60662. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60663. return _this;
  60664. }
  60665. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60666. /**
  60667. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60668. * This margin is expressed in world space coordinates, so its value may vary.
  60669. * Default value is 0.1
  60670. * @returns the intersection Threshold value.
  60671. */
  60672. get: function () {
  60673. return this._intersectionThreshold;
  60674. },
  60675. /**
  60676. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60677. * This margin is expressed in world space coordinates, so its value may vary.
  60678. * @param value the new threshold to apply
  60679. */
  60680. set: function (value) {
  60681. if (this._intersectionThreshold === value) {
  60682. return;
  60683. }
  60684. this._intersectionThreshold = value;
  60685. if (this.geometry) {
  60686. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60687. }
  60688. },
  60689. enumerable: true,
  60690. configurable: true
  60691. });
  60692. /**
  60693. * Returns the string "LineMesh"
  60694. */
  60695. LinesMesh.prototype.getClassName = function () {
  60696. return "LinesMesh";
  60697. };
  60698. Object.defineProperty(LinesMesh.prototype, "material", {
  60699. get: function () {
  60700. return this._colorShader;
  60701. },
  60702. set: function (value) {
  60703. // Do nothing
  60704. },
  60705. enumerable: true,
  60706. configurable: true
  60707. });
  60708. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60709. get: function () {
  60710. return false;
  60711. },
  60712. enumerable: true,
  60713. configurable: true
  60714. });
  60715. LinesMesh.prototype.createInstance = function (name) {
  60716. throw new Error("LinesMeshes do not support createInstance.");
  60717. };
  60718. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60719. if (!this._geometry) {
  60720. return this;
  60721. }
  60722. // VBOs
  60723. this._geometry._bind(this._colorShader.getEffect());
  60724. // Color
  60725. if (!this.useVertexColor) {
  60726. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60727. }
  60728. return this;
  60729. };
  60730. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60731. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60732. return this;
  60733. }
  60734. var engine = this.getScene().getEngine();
  60735. // Draw order
  60736. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60737. return this;
  60738. };
  60739. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60740. this._colorShader.dispose();
  60741. _super.prototype.dispose.call(this, doNotRecurse);
  60742. };
  60743. /**
  60744. * Returns a new LineMesh object cloned from the current one.
  60745. */
  60746. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60747. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60748. };
  60749. return LinesMesh;
  60750. }(BABYLON.Mesh));
  60751. BABYLON.LinesMesh = LinesMesh;
  60752. })(BABYLON || (BABYLON = {}));
  60753. //# sourceMappingURL=babylon.linesMesh.js.map
  60754. var BABYLON;
  60755. (function (BABYLON) {
  60756. /**
  60757. * Class containing static functions to help procedurally build meshes
  60758. */
  60759. var MeshBuilder = /** @class */ (function () {
  60760. function MeshBuilder() {
  60761. }
  60762. MeshBuilder.updateSideOrientation = function (orientation) {
  60763. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60764. return BABYLON.Mesh.DOUBLESIDE;
  60765. }
  60766. if (orientation === undefined || orientation === null) {
  60767. return BABYLON.Mesh.FRONTSIDE;
  60768. }
  60769. return orientation;
  60770. };
  60771. /**
  60772. * Creates a box mesh
  60773. * * The parameter `size` sets the size (float) of each box side (default 1)
  60774. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60775. * * 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)
  60776. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60777. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60778. * * 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
  60779. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60780. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60781. * @param name defines the name of the mesh
  60782. * @param options defines the options used to create the mesh
  60783. * @param scene defines the hosting scene
  60784. * @returns the box mesh
  60785. */
  60786. MeshBuilder.CreateBox = function (name, options, scene) {
  60787. if (scene === void 0) { scene = null; }
  60788. var box = new BABYLON.Mesh(name, scene);
  60789. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60790. box._originalBuilderSideOrientation = options.sideOrientation;
  60791. var vertexData = BABYLON.VertexData.CreateBox(options);
  60792. vertexData.applyToMesh(box, options.updatable);
  60793. return box;
  60794. };
  60795. /**
  60796. * Creates a sphere mesh
  60797. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60798. * * 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`)
  60799. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60800. * * 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
  60801. * * 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)
  60802. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60803. * * 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
  60804. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60805. * @param name defines the name of the mesh
  60806. * @param options defines the options used to create the mesh
  60807. * @param scene defines the hosting scene
  60808. * @returns the sphere mesh
  60809. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60810. */
  60811. MeshBuilder.CreateSphere = function (name, options, scene) {
  60812. var sphere = new BABYLON.Mesh(name, scene);
  60813. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60814. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60815. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60816. vertexData.applyToMesh(sphere, options.updatable);
  60817. return sphere;
  60818. };
  60819. /**
  60820. * Creates a plane polygonal mesh. By default, this is a disc
  60821. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60822. * * 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
  60823. * * 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
  60824. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60825. * * 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
  60826. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60827. * @param name defines the name of the mesh
  60828. * @param options defines the options used to create the mesh
  60829. * @param scene defines the hosting scene
  60830. * @returns the plane polygonal mesh
  60831. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60832. */
  60833. MeshBuilder.CreateDisc = function (name, options, scene) {
  60834. if (scene === void 0) { scene = null; }
  60835. var disc = new BABYLON.Mesh(name, scene);
  60836. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60837. disc._originalBuilderSideOrientation = options.sideOrientation;
  60838. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60839. vertexData.applyToMesh(disc, options.updatable);
  60840. return disc;
  60841. };
  60842. /**
  60843. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60844. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60845. * * 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`)
  60846. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60847. * * 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
  60848. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60849. * * 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
  60850. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60851. * @param name defines the name of the mesh
  60852. * @param options defines the options used to create the mesh
  60853. * @param scene defines the hosting scene
  60854. * @returns the icosahedron mesh
  60855. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60856. */
  60857. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60858. var sphere = new BABYLON.Mesh(name, scene);
  60859. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60860. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60861. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60862. vertexData.applyToMesh(sphere, options.updatable);
  60863. return sphere;
  60864. };
  60865. ;
  60866. /**
  60867. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60868. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60869. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60870. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60871. * * 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
  60872. * * 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
  60873. * * 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
  60874. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60875. * * 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
  60876. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60877. * * 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
  60878. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60879. * * 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
  60880. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60881. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60882. * @param name defines the name of the mesh
  60883. * @param options defines the options used to create the mesh
  60884. * @param scene defines the hosting scene
  60885. * @returns the ribbon mesh
  60886. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60887. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60888. */
  60889. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60890. if (scene === void 0) { scene = null; }
  60891. var pathArray = options.pathArray;
  60892. var closeArray = options.closeArray;
  60893. var closePath = options.closePath;
  60894. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60895. var instance = options.instance;
  60896. var updatable = options.updatable;
  60897. if (instance) { // existing ribbon instance update
  60898. // positionFunction : ribbon case
  60899. // only pathArray and sideOrientation parameters are taken into account for positions update
  60900. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60901. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60902. var positionFunction = function (positions) {
  60903. var minlg = pathArray[0].length;
  60904. var i = 0;
  60905. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60906. for (var si = 1; si <= ns; si++) {
  60907. for (var p = 0; p < pathArray.length; p++) {
  60908. var path = pathArray[p];
  60909. var l = path.length;
  60910. minlg = (minlg < l) ? minlg : l;
  60911. var j = 0;
  60912. while (j < minlg) {
  60913. positions[i] = path[j].x;
  60914. positions[i + 1] = path[j].y;
  60915. positions[i + 2] = path[j].z;
  60916. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60917. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60918. }
  60919. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60920. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60921. }
  60922. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60923. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60924. }
  60925. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60926. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60927. }
  60928. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60929. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60930. }
  60931. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60932. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60933. }
  60934. j++;
  60935. i += 3;
  60936. }
  60937. if (instance._closePath) {
  60938. positions[i] = path[0].x;
  60939. positions[i + 1] = path[0].y;
  60940. positions[i + 2] = path[0].z;
  60941. i += 3;
  60942. }
  60943. }
  60944. }
  60945. };
  60946. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60947. positionFunction(positions);
  60948. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60949. instance._boundingInfo.update(instance._worldMatrix);
  60950. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60951. if (options.colors) {
  60952. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60953. for (var c = 0; c < options.colors.length; c++) {
  60954. colors[c * 4] = options.colors[c].r;
  60955. colors[c * 4 + 1] = options.colors[c].g;
  60956. colors[c * 4 + 2] = options.colors[c].b;
  60957. colors[c * 4 + 3] = options.colors[c].a;
  60958. }
  60959. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60960. }
  60961. if (options.uvs) {
  60962. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60963. for (var i = 0; i < options.uvs.length; i++) {
  60964. uvs[i * 2] = options.uvs[i].x;
  60965. uvs[i * 2 + 1] = options.uvs[i].y;
  60966. }
  60967. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60968. }
  60969. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60970. var indices = instance.getIndices();
  60971. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60972. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60973. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60974. if (instance._closePath) {
  60975. var indexFirst = 0;
  60976. var indexLast = 0;
  60977. for (var p = 0; p < pathArray.length; p++) {
  60978. indexFirst = instance._idx[p] * 3;
  60979. if (p + 1 < pathArray.length) {
  60980. indexLast = (instance._idx[p + 1] - 1) * 3;
  60981. }
  60982. else {
  60983. indexLast = normals.length - 3;
  60984. }
  60985. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60986. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60987. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60988. normals[indexLast] = normals[indexFirst];
  60989. normals[indexLast + 1] = normals[indexFirst + 1];
  60990. normals[indexLast + 2] = normals[indexFirst + 2];
  60991. }
  60992. }
  60993. if (!(instance.areNormalsFrozen)) {
  60994. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60995. }
  60996. }
  60997. return instance;
  60998. }
  60999. else { // new ribbon creation
  61000. var ribbon = new BABYLON.Mesh(name, scene);
  61001. ribbon._originalBuilderSideOrientation = sideOrientation;
  61002. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61003. if (closePath) {
  61004. ribbon._idx = vertexData._idx;
  61005. }
  61006. ribbon._closePath = closePath;
  61007. ribbon._closeArray = closeArray;
  61008. vertexData.applyToMesh(ribbon, updatable);
  61009. return ribbon;
  61010. }
  61011. };
  61012. /**
  61013. * Creates a cylinder or a cone mesh
  61014. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61015. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61016. * * 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.
  61017. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61018. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61019. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61020. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61021. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61022. * * 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).
  61023. * * 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
  61024. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61025. * * 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
  61026. * * 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.
  61027. * * If `enclose` is false, a ring surface is one element.
  61028. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61029. * * 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
  61030. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61031. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61032. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61033. * @param name defines the name of the mesh
  61034. * @param options defines the options used to create the mesh
  61035. * @param scene defines the hosting scene
  61036. * @returns the cylinder mesh
  61037. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61038. */
  61039. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61040. var cylinder = new BABYLON.Mesh(name, scene);
  61041. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61042. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61043. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61044. vertexData.applyToMesh(cylinder, options.updatable);
  61045. return cylinder;
  61046. };
  61047. /**
  61048. * Creates a torus mesh
  61049. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61050. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61051. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61052. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61053. * * 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
  61054. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61055. * @param name defines the name of the mesh
  61056. * @param options defines the options used to create the mesh
  61057. * @param scene defines the hosting scene
  61058. * @returns the torus mesh
  61059. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61060. */
  61061. MeshBuilder.CreateTorus = function (name, options, scene) {
  61062. var torus = new BABYLON.Mesh(name, scene);
  61063. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61064. torus._originalBuilderSideOrientation = options.sideOrientation;
  61065. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61066. vertexData.applyToMesh(torus, options.updatable);
  61067. return torus;
  61068. };
  61069. /**
  61070. * Creates a torus knot mesh
  61071. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61072. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61073. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61074. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61075. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61076. * * 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
  61077. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61078. * @param name defines the name of the mesh
  61079. * @param options defines the options used to create the mesh
  61080. * @param scene defines the hosting scene
  61081. * @returns the torus knot mesh
  61082. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61083. */
  61084. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61085. var torusKnot = new BABYLON.Mesh(name, scene);
  61086. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61087. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61088. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61089. vertexData.applyToMesh(torusKnot, options.updatable);
  61090. return torusKnot;
  61091. };
  61092. /**
  61093. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61094. * * 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
  61095. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61096. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61097. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61098. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61099. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61100. * * 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
  61101. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61102. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61103. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61104. * @param name defines the name of the new line system
  61105. * @param options defines the options used to create the line system
  61106. * @param scene defines the hosting scene
  61107. * @returns a new line system mesh
  61108. */
  61109. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61110. var instance = options.instance;
  61111. var lines = options.lines;
  61112. var colors = options.colors;
  61113. if (instance) { // lines update
  61114. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61115. var vertexColor;
  61116. var lineColors;
  61117. if (colors) {
  61118. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61119. }
  61120. var i = 0;
  61121. var c = 0;
  61122. for (var l = 0; l < lines.length; l++) {
  61123. var points = lines[l];
  61124. for (var p = 0; p < points.length; p++) {
  61125. positions[i] = points[p].x;
  61126. positions[i + 1] = points[p].y;
  61127. positions[i + 2] = points[p].z;
  61128. if (colors && vertexColor) {
  61129. lineColors = colors[l];
  61130. vertexColor[c] = lineColors[p].r;
  61131. vertexColor[c + 1] = lineColors[p].g;
  61132. vertexColor[c + 2] = lineColors[p].b;
  61133. vertexColor[c + 3] = lineColors[p].a;
  61134. c += 4;
  61135. }
  61136. i += 3;
  61137. }
  61138. }
  61139. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61140. if (colors && vertexColor) {
  61141. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61142. }
  61143. return instance;
  61144. }
  61145. // line system creation
  61146. var useVertexColor = (colors) ? true : false;
  61147. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61148. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61149. vertexData.applyToMesh(lineSystem, options.updatable);
  61150. return lineSystem;
  61151. };
  61152. /**
  61153. * Creates a line mesh
  61154. * 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
  61155. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61156. * * The parameter `points` is an array successive Vector3
  61157. * * 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
  61158. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61159. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61160. * * When updating an instance, remember that only point positions can change, not the number of points
  61161. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61162. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61163. * @param name defines the name of the new line system
  61164. * @param options defines the options used to create the line system
  61165. * @param scene defines the hosting scene
  61166. * @returns a new line mesh
  61167. */
  61168. MeshBuilder.CreateLines = function (name, options, scene) {
  61169. if (scene === void 0) { scene = null; }
  61170. var colors = (options.colors) ? [options.colors] : null;
  61171. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61172. return lines;
  61173. };
  61174. /**
  61175. * Creates a dashed line mesh
  61176. * * 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
  61177. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61178. * * The parameter `points` is an array successive Vector3
  61179. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61180. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61181. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61182. * * 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
  61183. * * When updating an instance, remember that only point positions can change, not the number of points
  61184. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61185. * @param name defines the name of the mesh
  61186. * @param options defines the options used to create the mesh
  61187. * @param scene defines the hosting scene
  61188. * @returns the dashed line mesh
  61189. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61190. */
  61191. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61192. if (scene === void 0) { scene = null; }
  61193. var points = options.points;
  61194. var instance = options.instance;
  61195. var gapSize = options.gapSize || 1;
  61196. var dashSize = options.dashSize || 3;
  61197. if (instance) { // dashed lines update
  61198. var positionFunction = function (positions) {
  61199. var curvect = BABYLON.Vector3.Zero();
  61200. var nbSeg = positions.length / 6;
  61201. var lg = 0;
  61202. var nb = 0;
  61203. var shft = 0;
  61204. var dashshft = 0;
  61205. var curshft = 0;
  61206. var p = 0;
  61207. var i = 0;
  61208. var j = 0;
  61209. for (i = 0; i < points.length - 1; i++) {
  61210. points[i + 1].subtractToRef(points[i], curvect);
  61211. lg += curvect.length();
  61212. }
  61213. shft = lg / nbSeg;
  61214. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61215. for (i = 0; i < points.length - 1; i++) {
  61216. points[i + 1].subtractToRef(points[i], curvect);
  61217. nb = Math.floor(curvect.length() / shft);
  61218. curvect.normalize();
  61219. j = 0;
  61220. while (j < nb && p < positions.length) {
  61221. curshft = shft * j;
  61222. positions[p] = points[i].x + curshft * curvect.x;
  61223. positions[p + 1] = points[i].y + curshft * curvect.y;
  61224. positions[p + 2] = points[i].z + curshft * curvect.z;
  61225. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61226. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61227. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61228. p += 6;
  61229. j++;
  61230. }
  61231. }
  61232. while (p < positions.length) {
  61233. positions[p] = points[i].x;
  61234. positions[p + 1] = points[i].y;
  61235. positions[p + 2] = points[i].z;
  61236. p += 3;
  61237. }
  61238. };
  61239. instance.updateMeshPositions(positionFunction, false);
  61240. return instance;
  61241. }
  61242. // dashed lines creation
  61243. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61244. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61245. vertexData.applyToMesh(dashedLines, options.updatable);
  61246. dashedLines.dashSize = dashSize;
  61247. dashedLines.gapSize = gapSize;
  61248. return dashedLines;
  61249. };
  61250. /**
  61251. * 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.
  61252. * * 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.
  61253. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61254. * * 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.
  61255. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61256. * * 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
  61257. * * 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
  61258. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61259. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61260. * * 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
  61261. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61262. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61263. * @param name defines the name of the mesh
  61264. * @param options defines the options used to create the mesh
  61265. * @param scene defines the hosting scene
  61266. * @returns the extruded shape mesh
  61267. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61268. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61269. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61270. */
  61271. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61272. if (scene === void 0) { scene = null; }
  61273. var path = options.path;
  61274. var shape = options.shape;
  61275. var scale = options.scale || 1;
  61276. var rotation = options.rotation || 0;
  61277. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61278. var updatable = options.updatable;
  61279. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61280. var instance = options.instance || null;
  61281. var invertUV = options.invertUV || false;
  61282. 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);
  61283. };
  61284. /**
  61285. * Creates an custom extruded shape mesh.
  61286. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61287. * * 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.
  61288. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61289. * * 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
  61290. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61291. * * 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
  61292. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61293. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61294. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61295. * * 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
  61296. * * 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
  61297. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61298. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61299. * * 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
  61300. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61301. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61302. * @param name defines the name of the mesh
  61303. * @param options defines the options used to create the mesh
  61304. * @param scene defines the hosting scene
  61305. * @returns the custom extruded shape mesh
  61306. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61307. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61308. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61309. */
  61310. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61311. var path = options.path;
  61312. var shape = options.shape;
  61313. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61314. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61315. var ribbonCloseArray = options.ribbonCloseArray || false;
  61316. var ribbonClosePath = options.ribbonClosePath || false;
  61317. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61318. var updatable = options.updatable;
  61319. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61320. var instance = options.instance;
  61321. var invertUV = options.invertUV || false;
  61322. 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);
  61323. };
  61324. /**
  61325. * Creates lathe mesh.
  61326. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61327. * * 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
  61328. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61329. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61330. * * 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
  61331. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61332. * * 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
  61333. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61334. * * 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
  61335. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61336. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61337. * @param name defines the name of the mesh
  61338. * @param options defines the options used to create the mesh
  61339. * @param scene defines the hosting scene
  61340. * @returns the lathe mesh
  61341. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61342. */
  61343. MeshBuilder.CreateLathe = function (name, options, scene) {
  61344. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61345. var closed = (options.closed === undefined) ? true : options.closed;
  61346. var shape = options.shape;
  61347. var radius = options.radius || 1;
  61348. var tessellation = options.tessellation || 64;
  61349. var updatable = options.updatable;
  61350. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61351. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61352. var pi2 = Math.PI * 2;
  61353. var paths = new Array();
  61354. var invertUV = options.invertUV || false;
  61355. var i = 0;
  61356. var p = 0;
  61357. var step = pi2 / tessellation * arc;
  61358. var rotated;
  61359. var path = new Array();
  61360. for (i = 0; i <= tessellation; i++) {
  61361. var path = [];
  61362. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61363. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61364. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61365. }
  61366. for (p = 0; p < shape.length; p++) {
  61367. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61368. path.push(rotated);
  61369. }
  61370. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61371. 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));
  61372. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61373. }
  61374. paths.push(path);
  61375. }
  61376. // lathe ribbon
  61377. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61378. return lathe;
  61379. };
  61380. /**
  61381. * Creates a plane mesh
  61382. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61383. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61384. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61385. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61386. * * 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
  61387. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61388. * @param name defines the name of the mesh
  61389. * @param options defines the options used to create the mesh
  61390. * @param scene defines the hosting scene
  61391. * @returns the plane mesh
  61392. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61393. */
  61394. MeshBuilder.CreatePlane = function (name, options, scene) {
  61395. var plane = new BABYLON.Mesh(name, scene);
  61396. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61397. plane._originalBuilderSideOrientation = options.sideOrientation;
  61398. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61399. vertexData.applyToMesh(plane, options.updatable);
  61400. if (options.sourcePlane) {
  61401. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61402. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61403. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61404. plane.rotate(vectorProduct, product);
  61405. }
  61406. return plane;
  61407. };
  61408. /**
  61409. * Creates a ground mesh
  61410. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61411. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61412. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61413. * @param name defines the name of the mesh
  61414. * @param options defines the options used to create the mesh
  61415. * @param scene defines the hosting scene
  61416. * @returns the ground mesh
  61417. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61418. */
  61419. MeshBuilder.CreateGround = function (name, options, scene) {
  61420. var ground = new BABYLON.GroundMesh(name, scene);
  61421. ground._setReady(false);
  61422. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61423. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61424. ground._width = options.width || 1;
  61425. ground._height = options.height || 1;
  61426. ground._maxX = ground._width / 2;
  61427. ground._maxZ = ground._height / 2;
  61428. ground._minX = -ground._maxX;
  61429. ground._minZ = -ground._maxZ;
  61430. var vertexData = BABYLON.VertexData.CreateGround(options);
  61431. vertexData.applyToMesh(ground, options.updatable);
  61432. ground._setReady(true);
  61433. return ground;
  61434. };
  61435. /**
  61436. * Creates a tiled ground mesh
  61437. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61438. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61439. * * 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
  61440. * * 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
  61441. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61442. * @param name defines the name of the mesh
  61443. * @param options defines the options used to create the mesh
  61444. * @param scene defines the hosting scene
  61445. * @returns the tiled ground mesh
  61446. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61447. */
  61448. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61449. var tiledGround = new BABYLON.Mesh(name, scene);
  61450. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61451. vertexData.applyToMesh(tiledGround, options.updatable);
  61452. return tiledGround;
  61453. };
  61454. /**
  61455. * Creates a ground mesh from a height map
  61456. * * The parameter `url` sets the URL of the height map image resource.
  61457. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61458. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61459. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61460. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61461. * * 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.
  61462. * * 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).
  61463. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61464. * @param name defines the name of the mesh
  61465. * @param url defines the url to the height map
  61466. * @param options defines the options used to create the mesh
  61467. * @param scene defines the hosting scene
  61468. * @returns the ground mesh
  61469. * @see http://doc.babylonjs.com/babylon101/height_map
  61470. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61471. */
  61472. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61473. var width = options.width || 10.0;
  61474. var height = options.height || 10.0;
  61475. var subdivisions = options.subdivisions || 1 | 0;
  61476. var minHeight = options.minHeight || 0.0;
  61477. var maxHeight = options.maxHeight || 1.0;
  61478. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61479. var updatable = options.updatable;
  61480. var onReady = options.onReady;
  61481. var ground = new BABYLON.GroundMesh(name, scene);
  61482. ground._subdivisionsX = subdivisions;
  61483. ground._subdivisionsY = subdivisions;
  61484. ground._width = width;
  61485. ground._height = height;
  61486. ground._maxX = ground._width / 2.0;
  61487. ground._maxZ = ground._height / 2.0;
  61488. ground._minX = -ground._maxX;
  61489. ground._minZ = -ground._maxZ;
  61490. ground._setReady(false);
  61491. var onload = function (img) {
  61492. // Getting height map data
  61493. var canvas = document.createElement("canvas");
  61494. var context = canvas.getContext("2d");
  61495. if (!context) {
  61496. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61497. }
  61498. if (scene.isDisposed) {
  61499. return;
  61500. }
  61501. var bufferWidth = img.width;
  61502. var bufferHeight = img.height;
  61503. canvas.width = bufferWidth;
  61504. canvas.height = bufferHeight;
  61505. context.drawImage(img, 0, 0);
  61506. // Create VertexData from map data
  61507. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61508. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61509. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61510. width: width, height: height,
  61511. subdivisions: subdivisions,
  61512. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61513. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61514. });
  61515. vertexData.applyToMesh(ground, updatable);
  61516. //execute ready callback, if set
  61517. if (onReady) {
  61518. onReady(ground);
  61519. }
  61520. ground._setReady(true);
  61521. };
  61522. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61523. return ground;
  61524. };
  61525. /**
  61526. * Creates a polygon mesh
  61527. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61528. * * 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
  61529. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61530. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61531. * * 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)
  61532. * * Remember you can only change the shape positions, not their number when updating a polygon
  61533. * @param name defines the name of the mesh
  61534. * @param options defines the options used to create the mesh
  61535. * @param scene defines the hosting scene
  61536. * @returns the polygon mesh
  61537. */
  61538. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61539. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61540. var shape = options.shape;
  61541. var holes = options.holes || [];
  61542. var depth = options.depth || 0;
  61543. var contours = [];
  61544. var hole = [];
  61545. for (var i = 0; i < shape.length; i++) {
  61546. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61547. }
  61548. var epsilon = 0.00000001;
  61549. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61550. contours.pop();
  61551. }
  61552. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61553. for (var hNb = 0; hNb < holes.length; hNb++) {
  61554. hole = [];
  61555. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61556. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61557. }
  61558. polygonTriangulation.addHole(hole);
  61559. }
  61560. var polygon = polygonTriangulation.build(options.updatable, depth);
  61561. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61562. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61563. vertexData.applyToMesh(polygon, options.updatable);
  61564. return polygon;
  61565. };
  61566. ;
  61567. /**
  61568. * Creates an extruded polygon mesh, with depth in the Y direction.
  61569. * * 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)
  61570. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61571. * @param name defines the name of the mesh
  61572. * @param options defines the options used to create the mesh
  61573. * @param scene defines the hosting scene
  61574. * @returns the polygon mesh
  61575. */
  61576. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61577. return MeshBuilder.CreatePolygon(name, options, scene);
  61578. };
  61579. ;
  61580. /**
  61581. * Creates a tube mesh.
  61582. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61583. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61584. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61585. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61586. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61587. * * 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)
  61588. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61589. * * 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
  61590. * * 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
  61591. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61592. * * 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
  61593. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61594. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61595. * @param name defines the name of the mesh
  61596. * @param options defines the options used to create the mesh
  61597. * @param scene defines the hosting scene
  61598. * @returns the tube mesh
  61599. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61600. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61601. */
  61602. MeshBuilder.CreateTube = function (name, options, scene) {
  61603. var path = options.path;
  61604. var instance = options.instance;
  61605. var radius = 1.0;
  61606. if (instance) {
  61607. radius = instance.radius;
  61608. }
  61609. if (options.radius !== undefined) {
  61610. radius = options.radius;
  61611. }
  61612. ;
  61613. var tessellation = options.tessellation || 64 | 0;
  61614. var radiusFunction = options.radiusFunction || null;
  61615. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61616. var invertUV = options.invertUV || false;
  61617. var updatable = options.updatable;
  61618. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61619. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61620. // tube geometry
  61621. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61622. var tangents = path3D.getTangents();
  61623. var normals = path3D.getNormals();
  61624. var distances = path3D.getDistances();
  61625. var pi2 = Math.PI * 2;
  61626. var step = pi2 / tessellation * arc;
  61627. var returnRadius = function () { return radius; };
  61628. var radiusFunctionFinal = radiusFunction || returnRadius;
  61629. var circlePath;
  61630. var rad;
  61631. var normal;
  61632. var rotated;
  61633. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61634. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61635. for (var i = 0; i < path.length; i++) {
  61636. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61637. circlePath = Array(); // current circle array
  61638. normal = normals[i]; // current normal
  61639. for (var t = 0; t < tessellation; t++) {
  61640. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61641. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61642. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61643. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61644. circlePath[t] = rotated;
  61645. }
  61646. circlePaths[index] = circlePath;
  61647. index++;
  61648. }
  61649. // cap
  61650. var capPath = function (nbPoints, pathIndex) {
  61651. var pointCap = Array();
  61652. for (var i = 0; i < nbPoints; i++) {
  61653. pointCap.push(path[pathIndex]);
  61654. }
  61655. return pointCap;
  61656. };
  61657. switch (cap) {
  61658. case BABYLON.Mesh.NO_CAP:
  61659. break;
  61660. case BABYLON.Mesh.CAP_START:
  61661. circlePaths[0] = capPath(tessellation, 0);
  61662. circlePaths[1] = circlePaths[2].slice(0);
  61663. break;
  61664. case BABYLON.Mesh.CAP_END:
  61665. circlePaths[index] = circlePaths[index - 1].slice(0);
  61666. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61667. break;
  61668. case BABYLON.Mesh.CAP_ALL:
  61669. circlePaths[0] = capPath(tessellation, 0);
  61670. circlePaths[1] = circlePaths[2].slice(0);
  61671. circlePaths[index] = circlePaths[index - 1].slice(0);
  61672. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61673. break;
  61674. default:
  61675. break;
  61676. }
  61677. return circlePaths;
  61678. };
  61679. var path3D;
  61680. var pathArray;
  61681. if (instance) { // tube update
  61682. var arc = options.arc || instance.arc;
  61683. path3D = (instance.path3D).update(path);
  61684. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61685. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61686. instance.path3D = path3D;
  61687. instance.pathArray = pathArray;
  61688. instance.arc = arc;
  61689. instance.radius = radius;
  61690. return instance;
  61691. }
  61692. // tube creation
  61693. path3D = new BABYLON.Path3D(path);
  61694. var newPathArray = new Array();
  61695. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61696. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61697. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61698. tube.pathArray = pathArray;
  61699. tube.path3D = path3D;
  61700. tube.tessellation = tessellation;
  61701. tube.cap = cap;
  61702. tube.arc = options.arc;
  61703. tube.radius = radius;
  61704. return tube;
  61705. };
  61706. /**
  61707. * Creates a polyhedron mesh
  61708. * * 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
  61709. * * The parameter `size` (positive float, default 1) sets the polygon size
  61710. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61711. * * 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`
  61712. * * 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
  61713. * * 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)`)
  61714. * * 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
  61715. * * 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
  61716. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61717. * * 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
  61718. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61719. * @param name defines the name of the mesh
  61720. * @param options defines the options used to create the mesh
  61721. * @param scene defines the hosting scene
  61722. * @returns the polyhedron mesh
  61723. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61724. */
  61725. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61726. var polyhedron = new BABYLON.Mesh(name, scene);
  61727. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61728. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61729. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61730. vertexData.applyToMesh(polyhedron, options.updatable);
  61731. return polyhedron;
  61732. };
  61733. /**
  61734. * Creates a decal mesh.
  61735. * 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
  61736. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61737. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61738. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61739. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61740. * @param name defines the name of the mesh
  61741. * @param sourceMesh defines the mesh where the decal must be applied
  61742. * @param options defines the options used to create the mesh
  61743. * @param scene defines the hosting scene
  61744. * @returns the decal mesh
  61745. * @see http://doc.babylonjs.com/how_to/decals
  61746. */
  61747. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61748. var indices = sourceMesh.getIndices();
  61749. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61750. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61751. var position = options.position || BABYLON.Vector3.Zero();
  61752. var normal = options.normal || BABYLON.Vector3.Up();
  61753. var size = options.size || BABYLON.Vector3.One();
  61754. var angle = options.angle || 0;
  61755. // Getting correct rotation
  61756. if (!normal) {
  61757. var target = new BABYLON.Vector3(0, 0, 1);
  61758. var camera = sourceMesh.getScene().activeCamera;
  61759. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61760. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61761. }
  61762. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61763. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61764. var pitch = Math.atan2(normal.y, len);
  61765. // Matrix
  61766. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61767. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61768. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61769. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61770. var vertexData = new BABYLON.VertexData();
  61771. vertexData.indices = [];
  61772. vertexData.positions = [];
  61773. vertexData.normals = [];
  61774. vertexData.uvs = [];
  61775. var currentVertexDataIndex = 0;
  61776. var extractDecalVector3 = function (indexId) {
  61777. var result = new BABYLON.PositionNormalVertex();
  61778. if (!indices || !positions || !normals) {
  61779. return result;
  61780. }
  61781. var vertexId = indices[indexId];
  61782. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61783. // Send vector to decal local world
  61784. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61785. // Get normal
  61786. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61787. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61788. return result;
  61789. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61790. var clip = function (vertices, axis) {
  61791. if (vertices.length === 0) {
  61792. return vertices;
  61793. }
  61794. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61795. var clipVertices = function (v0, v1) {
  61796. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61797. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61798. };
  61799. var result = new Array();
  61800. for (var index = 0; index < vertices.length; index += 3) {
  61801. var v1Out;
  61802. var v2Out;
  61803. var v3Out;
  61804. var total = 0;
  61805. var nV1 = null;
  61806. var nV2 = null;
  61807. var nV3 = null;
  61808. var nV4 = null;
  61809. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61810. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61811. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61812. v1Out = d1 > 0;
  61813. v2Out = d2 > 0;
  61814. v3Out = d3 > 0;
  61815. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61816. switch (total) {
  61817. case 0:
  61818. result.push(vertices[index]);
  61819. result.push(vertices[index + 1]);
  61820. result.push(vertices[index + 2]);
  61821. break;
  61822. case 1:
  61823. if (v1Out) {
  61824. nV1 = vertices[index + 1];
  61825. nV2 = vertices[index + 2];
  61826. nV3 = clipVertices(vertices[index], nV1);
  61827. nV4 = clipVertices(vertices[index], nV2);
  61828. }
  61829. if (v2Out) {
  61830. nV1 = vertices[index];
  61831. nV2 = vertices[index + 2];
  61832. nV3 = clipVertices(vertices[index + 1], nV1);
  61833. nV4 = clipVertices(vertices[index + 1], nV2);
  61834. result.push(nV3);
  61835. result.push(nV2.clone());
  61836. result.push(nV1.clone());
  61837. result.push(nV2.clone());
  61838. result.push(nV3.clone());
  61839. result.push(nV4);
  61840. break;
  61841. }
  61842. if (v3Out) {
  61843. nV1 = vertices[index];
  61844. nV2 = vertices[index + 1];
  61845. nV3 = clipVertices(vertices[index + 2], nV1);
  61846. nV4 = clipVertices(vertices[index + 2], nV2);
  61847. }
  61848. if (nV1 && nV2 && nV3 && nV4) {
  61849. result.push(nV1.clone());
  61850. result.push(nV2.clone());
  61851. result.push(nV3);
  61852. result.push(nV4);
  61853. result.push(nV3.clone());
  61854. result.push(nV2.clone());
  61855. }
  61856. break;
  61857. case 2:
  61858. if (!v1Out) {
  61859. nV1 = vertices[index].clone();
  61860. nV2 = clipVertices(nV1, vertices[index + 1]);
  61861. nV3 = clipVertices(nV1, vertices[index + 2]);
  61862. result.push(nV1);
  61863. result.push(nV2);
  61864. result.push(nV3);
  61865. }
  61866. if (!v2Out) {
  61867. nV1 = vertices[index + 1].clone();
  61868. nV2 = clipVertices(nV1, vertices[index + 2]);
  61869. nV3 = clipVertices(nV1, vertices[index]);
  61870. result.push(nV1);
  61871. result.push(nV2);
  61872. result.push(nV3);
  61873. }
  61874. if (!v3Out) {
  61875. nV1 = vertices[index + 2].clone();
  61876. nV2 = clipVertices(nV1, vertices[index]);
  61877. nV3 = clipVertices(nV1, vertices[index + 1]);
  61878. result.push(nV1);
  61879. result.push(nV2);
  61880. result.push(nV3);
  61881. }
  61882. break;
  61883. case 3:
  61884. break;
  61885. }
  61886. }
  61887. return result;
  61888. };
  61889. for (var index = 0; index < indices.length; index += 3) {
  61890. var faceVertices = new Array();
  61891. faceVertices.push(extractDecalVector3(index));
  61892. faceVertices.push(extractDecalVector3(index + 1));
  61893. faceVertices.push(extractDecalVector3(index + 2));
  61894. // Clip
  61895. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61896. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61897. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61898. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61899. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61900. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61901. if (faceVertices.length === 0) {
  61902. continue;
  61903. }
  61904. // Add UVs and get back to world
  61905. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61906. var vertex = faceVertices[vIndex];
  61907. //TODO check for Int32Array | Uint32Array | Uint16Array
  61908. vertexData.indices.push(currentVertexDataIndex);
  61909. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61910. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61911. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61912. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61913. currentVertexDataIndex++;
  61914. }
  61915. }
  61916. // Return mesh
  61917. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61918. vertexData.applyToMesh(decal);
  61919. decal.position = position.clone();
  61920. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61921. return decal;
  61922. };
  61923. // Privates
  61924. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61925. // extrusion geometry
  61926. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61927. var tangents = path3D.getTangents();
  61928. var normals = path3D.getNormals();
  61929. var binormals = path3D.getBinormals();
  61930. var distances = path3D.getDistances();
  61931. var angle = 0;
  61932. var returnScale = function () { return scale !== null ? scale : 1; };
  61933. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61934. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61935. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61936. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61937. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61938. for (var i = 0; i < curve.length; i++) {
  61939. var shapePath = new Array();
  61940. var angleStep = rotate(i, distances[i]);
  61941. var scaleRatio = scl(i, distances[i]);
  61942. for (var p = 0; p < shape.length; p++) {
  61943. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61944. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61945. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61946. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61947. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61948. shapePath[p] = rotated;
  61949. }
  61950. shapePaths[index] = shapePath;
  61951. angle += angleStep;
  61952. index++;
  61953. }
  61954. // cap
  61955. var capPath = function (shapePath) {
  61956. var pointCap = Array();
  61957. var barycenter = BABYLON.Vector3.Zero();
  61958. var i;
  61959. for (i = 0; i < shapePath.length; i++) {
  61960. barycenter.addInPlace(shapePath[i]);
  61961. }
  61962. barycenter.scaleInPlace(1.0 / shapePath.length);
  61963. for (i = 0; i < shapePath.length; i++) {
  61964. pointCap.push(barycenter);
  61965. }
  61966. return pointCap;
  61967. };
  61968. switch (cap) {
  61969. case BABYLON.Mesh.NO_CAP:
  61970. break;
  61971. case BABYLON.Mesh.CAP_START:
  61972. shapePaths[0] = capPath(shapePaths[2]);
  61973. shapePaths[1] = shapePaths[2];
  61974. break;
  61975. case BABYLON.Mesh.CAP_END:
  61976. shapePaths[index] = shapePaths[index - 1];
  61977. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61978. break;
  61979. case BABYLON.Mesh.CAP_ALL:
  61980. shapePaths[0] = capPath(shapePaths[2]);
  61981. shapePaths[1] = shapePaths[2];
  61982. shapePaths[index] = shapePaths[index - 1];
  61983. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61984. break;
  61985. default:
  61986. break;
  61987. }
  61988. return shapePaths;
  61989. };
  61990. var path3D;
  61991. var pathArray;
  61992. if (instance) { // instance update
  61993. path3D = (instance.path3D).update(curve);
  61994. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61995. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61996. return instance;
  61997. }
  61998. // extruded shape creation
  61999. path3D = new BABYLON.Path3D(curve);
  62000. var newShapePaths = new Array();
  62001. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62002. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62003. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62004. extrudedGeneric.pathArray = pathArray;
  62005. extrudedGeneric.path3D = path3D;
  62006. extrudedGeneric.cap = cap;
  62007. return extrudedGeneric;
  62008. };
  62009. return MeshBuilder;
  62010. }());
  62011. BABYLON.MeshBuilder = MeshBuilder;
  62012. })(BABYLON || (BABYLON = {}));
  62013. //# sourceMappingURL=babylon.meshBuilder.js.map
  62014. var BABYLON;
  62015. (function (BABYLON) {
  62016. /**
  62017. * Draco compression (https://google.github.io/draco/)
  62018. *
  62019. * This class wraps the Draco module.
  62020. *
  62021. * **Encoder**
  62022. *
  62023. * The encoder is not currently implemented.
  62024. *
  62025. * **Decoder**
  62026. *
  62027. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62028. *
  62029. * To update the configuration, use the following code:
  62030. * ```javascript
  62031. * BABYLON.DracoCompression.Configuration = {
  62032. * decoder: {
  62033. * wasmUrl: "<url to the WebAssembly library>",
  62034. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62035. * fallbackUrl: "<url to the fallback JavaScript library>",
  62036. * }
  62037. * };
  62038. * ```
  62039. *
  62040. * 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.
  62041. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62042. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62043. *
  62044. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62045. * ```javascript
  62046. * var dracoCompression = new BABYLON.DracoCompression();
  62047. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62048. * [BABYLON.VertexBuffer.PositionKind]: 0
  62049. * });
  62050. * ```
  62051. *
  62052. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62053. */
  62054. var DracoCompression = /** @class */ (function () {
  62055. /**
  62056. * Constructor
  62057. */
  62058. function DracoCompression() {
  62059. }
  62060. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62061. /**
  62062. * Returns true if the decoder is available.
  62063. */
  62064. get: function () {
  62065. if (typeof DracoDecoderModule !== "undefined") {
  62066. return true;
  62067. }
  62068. var decoder = DracoCompression.Configuration.decoder;
  62069. if (decoder) {
  62070. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62071. return true;
  62072. }
  62073. if (decoder.fallbackUrl) {
  62074. return true;
  62075. }
  62076. }
  62077. return false;
  62078. },
  62079. enumerable: true,
  62080. configurable: true
  62081. });
  62082. /**
  62083. * Stop all async operations and release resources.
  62084. */
  62085. DracoCompression.prototype.dispose = function () {
  62086. };
  62087. /**
  62088. * Decode Draco compressed mesh data to vertex data.
  62089. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62090. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62091. * @returns A promise that resolves with the decoded vertex data
  62092. */
  62093. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62094. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62095. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62096. var module = wrappedModule.module;
  62097. var vertexData = new BABYLON.VertexData();
  62098. var buffer = new module.DecoderBuffer();
  62099. buffer.Init(dataView, dataView.byteLength);
  62100. var decoder = new module.Decoder();
  62101. var geometry;
  62102. var status;
  62103. try {
  62104. var type = decoder.GetEncodedGeometryType(buffer);
  62105. switch (type) {
  62106. case module.TRIANGULAR_MESH:
  62107. geometry = new module.Mesh();
  62108. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62109. break;
  62110. case module.POINT_CLOUD:
  62111. geometry = new module.PointCloud();
  62112. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62113. break;
  62114. default:
  62115. throw new Error("Invalid geometry type " + type);
  62116. }
  62117. if (!status.ok() || !geometry.ptr) {
  62118. throw new Error(status.error_msg());
  62119. }
  62120. var numPoints = geometry.num_points();
  62121. if (type === module.TRIANGULAR_MESH) {
  62122. var numFaces = geometry.num_faces();
  62123. var faceIndices = new module.DracoInt32Array();
  62124. try {
  62125. var indices = new Uint32Array(numFaces * 3);
  62126. for (var i = 0; i < numFaces; i++) {
  62127. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62128. var offset = i * 3;
  62129. indices[offset + 0] = faceIndices.GetValue(0);
  62130. indices[offset + 1] = faceIndices.GetValue(1);
  62131. indices[offset + 2] = faceIndices.GetValue(2);
  62132. }
  62133. vertexData.indices = indices;
  62134. }
  62135. finally {
  62136. module.destroy(faceIndices);
  62137. }
  62138. }
  62139. for (var kind in attributes) {
  62140. var uniqueId = attributes[kind];
  62141. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62142. var dracoData = new module.DracoFloat32Array();
  62143. try {
  62144. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62145. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62146. for (var i = 0; i < babylonData.length; i++) {
  62147. babylonData[i] = dracoData.GetValue(i);
  62148. }
  62149. vertexData.set(babylonData, kind);
  62150. }
  62151. finally {
  62152. module.destroy(dracoData);
  62153. }
  62154. }
  62155. }
  62156. finally {
  62157. if (geometry) {
  62158. module.destroy(geometry);
  62159. }
  62160. module.destroy(decoder);
  62161. module.destroy(buffer);
  62162. }
  62163. return vertexData;
  62164. });
  62165. };
  62166. DracoCompression._GetDecoderModule = function () {
  62167. if (!DracoCompression._DecoderModulePromise) {
  62168. var promise = null;
  62169. var config_1 = {};
  62170. if (typeof DracoDecoderModule !== "undefined") {
  62171. promise = Promise.resolve();
  62172. }
  62173. else {
  62174. var decoder = DracoCompression.Configuration.decoder;
  62175. if (decoder) {
  62176. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62177. promise = Promise.all([
  62178. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62179. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62180. config_1.wasmBinary = data;
  62181. })
  62182. ]);
  62183. }
  62184. else if (decoder.fallbackUrl) {
  62185. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62186. }
  62187. }
  62188. }
  62189. if (!promise) {
  62190. throw new Error("Draco decoder module is not available");
  62191. }
  62192. DracoCompression._DecoderModulePromise = promise.then(function () {
  62193. return new Promise(function (resolve) {
  62194. config_1.onModuleLoaded = function (decoderModule) {
  62195. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62196. resolve({ module: decoderModule });
  62197. };
  62198. DracoDecoderModule(config_1);
  62199. });
  62200. });
  62201. }
  62202. return DracoCompression._DecoderModulePromise;
  62203. };
  62204. DracoCompression._LoadScriptAsync = function (url) {
  62205. return new Promise(function (resolve, reject) {
  62206. BABYLON.Tools.LoadScript(url, function () {
  62207. resolve();
  62208. }, function (message) {
  62209. reject(new Error(message));
  62210. });
  62211. });
  62212. };
  62213. DracoCompression._LoadFileAsync = function (url) {
  62214. return new Promise(function (resolve, reject) {
  62215. BABYLON.Tools.LoadFile(url, function (data) {
  62216. resolve(data);
  62217. }, undefined, undefined, true, function (request, exception) {
  62218. reject(exception);
  62219. });
  62220. });
  62221. };
  62222. /**
  62223. * The configuration. Defaults to the following urls:
  62224. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62225. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62226. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62227. */
  62228. DracoCompression.Configuration = {
  62229. decoder: {
  62230. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62231. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62232. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62233. }
  62234. };
  62235. return DracoCompression;
  62236. }());
  62237. BABYLON.DracoCompression = DracoCompression;
  62238. })(BABYLON || (BABYLON = {}));
  62239. //# sourceMappingURL=babylon.dracoCompression.js.map
  62240. var BABYLON;
  62241. (function (BABYLON) {
  62242. var AudioEngine = /** @class */ (function () {
  62243. function AudioEngine() {
  62244. this._audioContext = null;
  62245. this._audioContextInitialized = false;
  62246. this.canUseWebAudio = false;
  62247. this.WarnedWebAudioUnsupported = false;
  62248. this.unlocked = false;
  62249. this.isMP3supported = false;
  62250. this.isOGGsupported = false;
  62251. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62252. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62253. this.canUseWebAudio = true;
  62254. }
  62255. var audioElem = document.createElement('audio');
  62256. try {
  62257. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62258. this.isMP3supported = true;
  62259. }
  62260. }
  62261. catch (e) {
  62262. // protect error during capability check.
  62263. }
  62264. try {
  62265. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62266. this.isOGGsupported = true;
  62267. }
  62268. }
  62269. catch (e) {
  62270. // protect error during capability check.
  62271. }
  62272. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62273. this._unlockiOSaudio();
  62274. }
  62275. else {
  62276. this.unlocked = true;
  62277. }
  62278. }
  62279. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62280. get: function () {
  62281. if (!this._audioContextInitialized) {
  62282. this._initializeAudioContext();
  62283. }
  62284. return this._audioContext;
  62285. },
  62286. enumerable: true,
  62287. configurable: true
  62288. });
  62289. AudioEngine.prototype._unlockiOSaudio = function () {
  62290. var _this = this;
  62291. var unlockaudio = function () {
  62292. if (!_this.audioContext) {
  62293. return;
  62294. }
  62295. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62296. var source = _this.audioContext.createBufferSource();
  62297. source.buffer = buffer;
  62298. source.connect(_this.audioContext.destination);
  62299. source.start(0);
  62300. setTimeout(function () {
  62301. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62302. _this.unlocked = true;
  62303. window.removeEventListener('touchend', unlockaudio, false);
  62304. if (_this.onAudioUnlocked) {
  62305. _this.onAudioUnlocked();
  62306. }
  62307. }
  62308. }, 0);
  62309. };
  62310. window.addEventListener('touchend', unlockaudio, false);
  62311. };
  62312. AudioEngine.prototype._initializeAudioContext = function () {
  62313. try {
  62314. if (this.canUseWebAudio) {
  62315. this._audioContext = new AudioContext();
  62316. // create a global volume gain node
  62317. this.masterGain = this._audioContext.createGain();
  62318. this.masterGain.gain.value = 1;
  62319. this.masterGain.connect(this._audioContext.destination);
  62320. this._audioContextInitialized = true;
  62321. }
  62322. }
  62323. catch (e) {
  62324. this.canUseWebAudio = false;
  62325. BABYLON.Tools.Error("Web Audio: " + e.message);
  62326. }
  62327. };
  62328. AudioEngine.prototype.dispose = function () {
  62329. if (this.canUseWebAudio && this._audioContextInitialized) {
  62330. if (this._connectedAnalyser && this._audioContext) {
  62331. this._connectedAnalyser.stopDebugCanvas();
  62332. this._connectedAnalyser.dispose();
  62333. this.masterGain.disconnect();
  62334. this.masterGain.connect(this._audioContext.destination);
  62335. this._connectedAnalyser = null;
  62336. }
  62337. this.masterGain.gain.value = 1;
  62338. }
  62339. this.WarnedWebAudioUnsupported = false;
  62340. };
  62341. AudioEngine.prototype.getGlobalVolume = function () {
  62342. if (this.canUseWebAudio && this._audioContextInitialized) {
  62343. return this.masterGain.gain.value;
  62344. }
  62345. else {
  62346. return -1;
  62347. }
  62348. };
  62349. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62350. if (this.canUseWebAudio && this._audioContextInitialized) {
  62351. this.masterGain.gain.value = newVolume;
  62352. }
  62353. };
  62354. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62355. if (this._connectedAnalyser) {
  62356. this._connectedAnalyser.stopDebugCanvas();
  62357. }
  62358. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62359. this._connectedAnalyser = analyser;
  62360. this.masterGain.disconnect();
  62361. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62362. }
  62363. };
  62364. return AudioEngine;
  62365. }());
  62366. BABYLON.AudioEngine = AudioEngine;
  62367. })(BABYLON || (BABYLON = {}));
  62368. //# sourceMappingURL=babylon.audioEngine.js.map
  62369. var BABYLON;
  62370. (function (BABYLON) {
  62371. var Sound = /** @class */ (function () {
  62372. /**
  62373. * Create a sound and attach it to a scene
  62374. * @param name Name of your sound
  62375. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  62376. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62377. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62378. */
  62379. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62380. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62381. var _this = this;
  62382. this.autoplay = false;
  62383. this.loop = false;
  62384. this.useCustomAttenuation = false;
  62385. this.spatialSound = false;
  62386. this.refDistance = 1;
  62387. this.rolloffFactor = 1;
  62388. this.maxDistance = 100;
  62389. this.distanceModel = "linear";
  62390. this._panningModel = "equalpower";
  62391. this._playbackRate = 1;
  62392. this._streaming = false;
  62393. this._startTime = 0;
  62394. this._startOffset = 0;
  62395. this._position = BABYLON.Vector3.Zero();
  62396. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62397. this._volume = 1;
  62398. this._isReadyToPlay = false;
  62399. this.isPlaying = false;
  62400. this.isPaused = false;
  62401. this._isDirectional = false;
  62402. // Used if you'd like to create a directional sound.
  62403. // If not set, the sound will be omnidirectional
  62404. this._coneInnerAngle = 360;
  62405. this._coneOuterAngle = 360;
  62406. this._coneOuterGain = 0;
  62407. this._isOutputConnected = false;
  62408. this._urlType = "Unknown";
  62409. this.name = name;
  62410. this._scene = scene;
  62411. this._readyToPlayCallback = readyToPlayCallback;
  62412. // Default custom attenuation function is a linear attenuation
  62413. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62414. if (currentDistance < maxDistance) {
  62415. return currentVolume * (1 - currentDistance / maxDistance);
  62416. }
  62417. else {
  62418. return 0;
  62419. }
  62420. };
  62421. if (options) {
  62422. this.autoplay = options.autoplay || false;
  62423. this.loop = options.loop || false;
  62424. // if volume === 0, we need another way to check this option
  62425. if (options.volume !== undefined) {
  62426. this._volume = options.volume;
  62427. }
  62428. this.spatialSound = options.spatialSound || false;
  62429. this.maxDistance = options.maxDistance || 100;
  62430. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62431. this.rolloffFactor = options.rolloffFactor || 1;
  62432. this.refDistance = options.refDistance || 1;
  62433. this.distanceModel = options.distanceModel || "linear";
  62434. this._playbackRate = options.playbackRate || 1;
  62435. this._streaming = options.streaming || false;
  62436. }
  62437. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62438. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62439. this._soundGain.gain.value = this._volume;
  62440. this._inputAudioNode = this._soundGain;
  62441. this._ouputAudioNode = this._soundGain;
  62442. if (this.spatialSound) {
  62443. this._createSpatialParameters();
  62444. }
  62445. this._scene.mainSoundTrack.AddSound(this);
  62446. var validParameter = true;
  62447. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62448. if (urlOrArrayBuffer) {
  62449. try {
  62450. if (typeof (urlOrArrayBuffer) === "string") {
  62451. this._urlType = "String";
  62452. }
  62453. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  62454. this._urlType = "ArrayBuffer";
  62455. }
  62456. else if (urlOrArrayBuffer instanceof MediaStream) {
  62457. this._urlType = "MediaStream";
  62458. }
  62459. else if (Array.isArray(urlOrArrayBuffer)) {
  62460. this._urlType = "Array";
  62461. }
  62462. var urls = [];
  62463. var codecSupportedFound = false;
  62464. switch (this._urlType) {
  62465. case "MediaStream":
  62466. this._streaming = true;
  62467. this._isReadyToPlay = true;
  62468. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  62469. if (this.autoplay) {
  62470. this.play();
  62471. }
  62472. if (this._readyToPlayCallback) {
  62473. this._readyToPlayCallback();
  62474. }
  62475. break;
  62476. case "ArrayBuffer":
  62477. if (urlOrArrayBuffer.byteLength > 0) {
  62478. codecSupportedFound = true;
  62479. this._soundLoaded(urlOrArrayBuffer);
  62480. }
  62481. break;
  62482. case "String":
  62483. urls.push(urlOrArrayBuffer);
  62484. case "Array":
  62485. if (urls.length === 0)
  62486. urls = urlOrArrayBuffer;
  62487. // If we found a supported format, we load it immediately and stop the loop
  62488. for (var i = 0; i < urls.length; i++) {
  62489. var url = urls[i];
  62490. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62491. codecSupportedFound = true;
  62492. }
  62493. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62494. codecSupportedFound = true;
  62495. }
  62496. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62497. codecSupportedFound = true;
  62498. }
  62499. if (url.indexOf("blob:") !== -1) {
  62500. codecSupportedFound = true;
  62501. }
  62502. if (codecSupportedFound) {
  62503. // Loading sound using XHR2
  62504. if (!this._streaming) {
  62505. this._scene._loadFile(url, function (data) {
  62506. _this._soundLoaded(data);
  62507. }, undefined, true, true, function (exception) {
  62508. if (exception) {
  62509. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62510. }
  62511. BABYLON.Tools.Error("Sound creation aborted.");
  62512. _this._scene.mainSoundTrack.RemoveSound(_this);
  62513. });
  62514. }
  62515. // Streaming sound using HTML5 Audio tag
  62516. else {
  62517. this._htmlAudioElement = new Audio(url);
  62518. this._htmlAudioElement.controls = false;
  62519. this._htmlAudioElement.loop = this.loop;
  62520. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62521. this._htmlAudioElement.preload = "auto";
  62522. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62523. _this._isReadyToPlay = true;
  62524. if (_this.autoplay) {
  62525. _this.play();
  62526. }
  62527. if (_this._readyToPlayCallback) {
  62528. _this._readyToPlayCallback();
  62529. }
  62530. });
  62531. document.body.appendChild(this._htmlAudioElement);
  62532. }
  62533. break;
  62534. }
  62535. }
  62536. break;
  62537. default:
  62538. validParameter = false;
  62539. break;
  62540. }
  62541. if (!validParameter) {
  62542. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62543. }
  62544. else {
  62545. if (!codecSupportedFound) {
  62546. this._isReadyToPlay = true;
  62547. // Simulating a ready to play event to avoid breaking code path
  62548. if (this._readyToPlayCallback) {
  62549. window.setTimeout(function () {
  62550. if (_this._readyToPlayCallback) {
  62551. _this._readyToPlayCallback();
  62552. }
  62553. }, 1000);
  62554. }
  62555. }
  62556. }
  62557. }
  62558. catch (ex) {
  62559. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62560. this._scene.mainSoundTrack.RemoveSound(this);
  62561. }
  62562. }
  62563. }
  62564. else {
  62565. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62566. this._scene.mainSoundTrack.AddSound(this);
  62567. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62568. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62569. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62570. }
  62571. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62572. if (this._readyToPlayCallback) {
  62573. window.setTimeout(function () {
  62574. if (_this._readyToPlayCallback) {
  62575. _this._readyToPlayCallback();
  62576. }
  62577. }, 1000);
  62578. }
  62579. }
  62580. }
  62581. Sound.prototype.dispose = function () {
  62582. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62583. if (this.isPlaying) {
  62584. this.stop();
  62585. }
  62586. this._isReadyToPlay = false;
  62587. if (this.soundTrackId === -1) {
  62588. this._scene.mainSoundTrack.RemoveSound(this);
  62589. }
  62590. else {
  62591. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62592. }
  62593. if (this._soundGain) {
  62594. this._soundGain.disconnect();
  62595. this._soundGain = null;
  62596. }
  62597. if (this._soundPanner) {
  62598. this._soundPanner.disconnect();
  62599. this._soundPanner = null;
  62600. }
  62601. if (this._soundSource) {
  62602. this._soundSource.disconnect();
  62603. this._soundSource = null;
  62604. }
  62605. this._audioBuffer = null;
  62606. if (this._htmlAudioElement) {
  62607. this._htmlAudioElement.pause();
  62608. this._htmlAudioElement.src = "";
  62609. document.body.removeChild(this._htmlAudioElement);
  62610. }
  62611. if (this._streamingSource) {
  62612. this._streamingSource.disconnect();
  62613. }
  62614. if (this._connectedMesh && this._registerFunc) {
  62615. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62616. this._connectedMesh = null;
  62617. }
  62618. }
  62619. };
  62620. Sound.prototype.isReady = function () {
  62621. return this._isReadyToPlay;
  62622. };
  62623. Sound.prototype._soundLoaded = function (audioData) {
  62624. var _this = this;
  62625. if (!BABYLON.Engine.audioEngine.audioContext) {
  62626. return;
  62627. }
  62628. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62629. _this._audioBuffer = buffer;
  62630. _this._isReadyToPlay = true;
  62631. if (_this.autoplay) {
  62632. _this.play();
  62633. }
  62634. if (_this._readyToPlayCallback) {
  62635. _this._readyToPlayCallback();
  62636. }
  62637. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62638. };
  62639. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62640. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62641. this._audioBuffer = audioBuffer;
  62642. this._isReadyToPlay = true;
  62643. }
  62644. };
  62645. Sound.prototype.updateOptions = function (options) {
  62646. if (options) {
  62647. this.loop = options.loop || this.loop;
  62648. this.maxDistance = options.maxDistance || this.maxDistance;
  62649. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62650. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62651. this.refDistance = options.refDistance || this.refDistance;
  62652. this.distanceModel = options.distanceModel || this.distanceModel;
  62653. this._playbackRate = options.playbackRate || this._playbackRate;
  62654. this._updateSpatialParameters();
  62655. if (this.isPlaying) {
  62656. if (this._streaming && this._htmlAudioElement) {
  62657. this._htmlAudioElement.playbackRate = this._playbackRate;
  62658. }
  62659. else {
  62660. if (this._soundSource) {
  62661. this._soundSource.playbackRate.value = this._playbackRate;
  62662. }
  62663. }
  62664. }
  62665. }
  62666. };
  62667. Sound.prototype._createSpatialParameters = function () {
  62668. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62669. if (this._scene.headphone) {
  62670. this._panningModel = "HRTF";
  62671. }
  62672. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62673. this._updateSpatialParameters();
  62674. this._soundPanner.connect(this._ouputAudioNode);
  62675. this._inputAudioNode = this._soundPanner;
  62676. }
  62677. };
  62678. Sound.prototype._updateSpatialParameters = function () {
  62679. if (this.spatialSound && this._soundPanner) {
  62680. if (this.useCustomAttenuation) {
  62681. // Tricks to disable in a way embedded Web Audio attenuation
  62682. this._soundPanner.distanceModel = "linear";
  62683. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62684. this._soundPanner.refDistance = 1;
  62685. this._soundPanner.rolloffFactor = 1;
  62686. this._soundPanner.panningModel = this._panningModel;
  62687. }
  62688. else {
  62689. this._soundPanner.distanceModel = this.distanceModel;
  62690. this._soundPanner.maxDistance = this.maxDistance;
  62691. this._soundPanner.refDistance = this.refDistance;
  62692. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62693. this._soundPanner.panningModel = this._panningModel;
  62694. }
  62695. }
  62696. };
  62697. Sound.prototype.switchPanningModelToHRTF = function () {
  62698. this._panningModel = "HRTF";
  62699. this._switchPanningModel();
  62700. };
  62701. Sound.prototype.switchPanningModelToEqualPower = function () {
  62702. this._panningModel = "equalpower";
  62703. this._switchPanningModel();
  62704. };
  62705. Sound.prototype._switchPanningModel = function () {
  62706. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62707. this._soundPanner.panningModel = this._panningModel;
  62708. }
  62709. };
  62710. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62711. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62712. if (this._isOutputConnected) {
  62713. this._ouputAudioNode.disconnect();
  62714. }
  62715. this._ouputAudioNode.connect(soundTrackAudioNode);
  62716. this._isOutputConnected = true;
  62717. }
  62718. };
  62719. /**
  62720. * Transform this sound into a directional source
  62721. * @param coneInnerAngle Size of the inner cone in degree
  62722. * @param coneOuterAngle Size of the outer cone in degree
  62723. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62724. */
  62725. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62726. if (coneOuterAngle < coneInnerAngle) {
  62727. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62728. return;
  62729. }
  62730. this._coneInnerAngle = coneInnerAngle;
  62731. this._coneOuterAngle = coneOuterAngle;
  62732. this._coneOuterGain = coneOuterGain;
  62733. this._isDirectional = true;
  62734. if (this.isPlaying && this.loop) {
  62735. this.stop();
  62736. this.play();
  62737. }
  62738. };
  62739. Sound.prototype.setPosition = function (newPosition) {
  62740. this._position = newPosition;
  62741. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62742. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62743. }
  62744. };
  62745. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62746. this._localDirection = newLocalDirection;
  62747. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62748. this._updateDirection();
  62749. }
  62750. };
  62751. Sound.prototype._updateDirection = function () {
  62752. if (!this._connectedMesh || !this._soundPanner) {
  62753. return;
  62754. }
  62755. var mat = this._connectedMesh.getWorldMatrix();
  62756. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62757. direction.normalize();
  62758. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62759. };
  62760. Sound.prototype.updateDistanceFromListener = function () {
  62761. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62762. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62763. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62764. }
  62765. };
  62766. Sound.prototype.setAttenuationFunction = function (callback) {
  62767. this._customAttenuationFunction = callback;
  62768. };
  62769. /**
  62770. * Play the sound
  62771. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62772. * @param offset (optional) Start the sound setting it at a specific time
  62773. */
  62774. Sound.prototype.play = function (time, offset) {
  62775. var _this = this;
  62776. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62777. try {
  62778. if (this._startOffset < 0) {
  62779. time = -this._startOffset;
  62780. this._startOffset = 0;
  62781. }
  62782. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62783. if (!this._soundSource || !this._streamingSource) {
  62784. if (this.spatialSound && this._soundPanner) {
  62785. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62786. if (this._isDirectional) {
  62787. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62788. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62789. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62790. if (this._connectedMesh) {
  62791. this._updateDirection();
  62792. }
  62793. else {
  62794. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62795. }
  62796. }
  62797. }
  62798. }
  62799. if (this._streaming) {
  62800. if (!this._streamingSource) {
  62801. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62802. this._htmlAudioElement.onended = function () { _this._onended(); };
  62803. this._htmlAudioElement.playbackRate = this._playbackRate;
  62804. }
  62805. this._streamingSource.disconnect();
  62806. this._streamingSource.connect(this._inputAudioNode);
  62807. if (this._htmlAudioElement) {
  62808. this._htmlAudioElement.play();
  62809. }
  62810. }
  62811. else {
  62812. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62813. this._soundSource.buffer = this._audioBuffer;
  62814. this._soundSource.connect(this._inputAudioNode);
  62815. this._soundSource.loop = this.loop;
  62816. this._soundSource.playbackRate.value = this._playbackRate;
  62817. this._soundSource.onended = function () { _this._onended(); };
  62818. if (this._soundSource.buffer) {
  62819. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62820. }
  62821. }
  62822. this._startTime = startTime;
  62823. this.isPlaying = true;
  62824. this.isPaused = false;
  62825. }
  62826. catch (ex) {
  62827. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62828. }
  62829. }
  62830. };
  62831. Sound.prototype._onended = function () {
  62832. this.isPlaying = false;
  62833. if (this.onended) {
  62834. this.onended();
  62835. }
  62836. };
  62837. /**
  62838. * Stop the sound
  62839. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62840. */
  62841. Sound.prototype.stop = function (time) {
  62842. if (this.isPlaying) {
  62843. if (this._streaming) {
  62844. if (this._htmlAudioElement) {
  62845. this._htmlAudioElement.pause();
  62846. // Test needed for Firefox or it will generate an Invalid State Error
  62847. if (this._htmlAudioElement.currentTime > 0) {
  62848. this._htmlAudioElement.currentTime = 0;
  62849. }
  62850. }
  62851. else {
  62852. this._streamingSource.disconnect();
  62853. }
  62854. }
  62855. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62856. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62857. this._soundSource.stop(stopTime);
  62858. this._soundSource.onended = function () { };
  62859. if (!this.isPaused) {
  62860. this._startOffset = 0;
  62861. }
  62862. }
  62863. this.isPlaying = false;
  62864. }
  62865. };
  62866. Sound.prototype.pause = function () {
  62867. if (this.isPlaying) {
  62868. this.isPaused = true;
  62869. if (this._streaming) {
  62870. if (this._htmlAudioElement) {
  62871. this._htmlAudioElement.pause();
  62872. }
  62873. else {
  62874. this._streamingSource.disconnect();
  62875. }
  62876. }
  62877. else if (BABYLON.Engine.audioEngine.audioContext) {
  62878. this.stop(0);
  62879. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62880. }
  62881. }
  62882. };
  62883. Sound.prototype.setVolume = function (newVolume, time) {
  62884. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62885. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62886. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62887. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62888. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62889. }
  62890. else {
  62891. this._soundGain.gain.value = newVolume;
  62892. }
  62893. }
  62894. this._volume = newVolume;
  62895. };
  62896. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62897. this._playbackRate = newPlaybackRate;
  62898. if (this.isPlaying) {
  62899. if (this._streaming && this._htmlAudioElement) {
  62900. this._htmlAudioElement.playbackRate = this._playbackRate;
  62901. }
  62902. else if (this._soundSource) {
  62903. this._soundSource.playbackRate.value = this._playbackRate;
  62904. }
  62905. }
  62906. };
  62907. Sound.prototype.getVolume = function () {
  62908. return this._volume;
  62909. };
  62910. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62911. var _this = this;
  62912. if (this._connectedMesh && this._registerFunc) {
  62913. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62914. this._registerFunc = null;
  62915. }
  62916. this._connectedMesh = meshToConnectTo;
  62917. if (!this.spatialSound) {
  62918. this.spatialSound = true;
  62919. this._createSpatialParameters();
  62920. if (this.isPlaying && this.loop) {
  62921. this.stop();
  62922. this.play();
  62923. }
  62924. }
  62925. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62926. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62927. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62928. };
  62929. Sound.prototype.detachFromMesh = function () {
  62930. if (this._connectedMesh && this._registerFunc) {
  62931. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62932. this._registerFunc = null;
  62933. this._connectedMesh = null;
  62934. }
  62935. };
  62936. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62937. if (!node.getBoundingInfo) {
  62938. return;
  62939. }
  62940. var mesh = node;
  62941. var boundingInfo = mesh.getBoundingInfo();
  62942. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62943. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62944. this._updateDirection();
  62945. }
  62946. };
  62947. Sound.prototype.clone = function () {
  62948. var _this = this;
  62949. if (!this._streaming) {
  62950. var setBufferAndRun = function () {
  62951. if (_this._isReadyToPlay) {
  62952. clonedSound._audioBuffer = _this.getAudioBuffer();
  62953. clonedSound._isReadyToPlay = true;
  62954. if (clonedSound.autoplay) {
  62955. clonedSound.play();
  62956. }
  62957. }
  62958. else {
  62959. window.setTimeout(setBufferAndRun, 300);
  62960. }
  62961. };
  62962. var currentOptions = {
  62963. autoplay: this.autoplay, loop: this.loop,
  62964. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62965. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62966. refDistance: this.refDistance, distanceModel: this.distanceModel
  62967. };
  62968. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62969. if (this.useCustomAttenuation) {
  62970. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62971. }
  62972. clonedSound.setPosition(this._position);
  62973. clonedSound.setPlaybackRate(this._playbackRate);
  62974. setBufferAndRun();
  62975. return clonedSound;
  62976. }
  62977. // Can't clone a streaming sound
  62978. else {
  62979. return null;
  62980. }
  62981. };
  62982. Sound.prototype.getAudioBuffer = function () {
  62983. return this._audioBuffer;
  62984. };
  62985. Sound.prototype.serialize = function () {
  62986. var serializationObject = {
  62987. name: this.name,
  62988. url: this.name,
  62989. autoplay: this.autoplay,
  62990. loop: this.loop,
  62991. volume: this._volume,
  62992. spatialSound: this.spatialSound,
  62993. maxDistance: this.maxDistance,
  62994. rolloffFactor: this.rolloffFactor,
  62995. refDistance: this.refDistance,
  62996. distanceModel: this.distanceModel,
  62997. playbackRate: this._playbackRate,
  62998. panningModel: this._panningModel,
  62999. soundTrackId: this.soundTrackId
  63000. };
  63001. if (this.spatialSound) {
  63002. if (this._connectedMesh)
  63003. serializationObject.connectedMeshId = this._connectedMesh.id;
  63004. serializationObject.position = this._position.asArray();
  63005. serializationObject.refDistance = this.refDistance;
  63006. serializationObject.distanceModel = this.distanceModel;
  63007. serializationObject.isDirectional = this._isDirectional;
  63008. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63009. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63010. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63011. serializationObject.coneOuterGain = this._coneOuterGain;
  63012. }
  63013. return serializationObject;
  63014. };
  63015. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63016. var soundName = parsedSound.name;
  63017. var soundUrl;
  63018. if (parsedSound.url) {
  63019. soundUrl = rootUrl + parsedSound.url;
  63020. }
  63021. else {
  63022. soundUrl = rootUrl + soundName;
  63023. }
  63024. var options = {
  63025. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63026. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63027. rolloffFactor: parsedSound.rolloffFactor,
  63028. refDistance: parsedSound.refDistance,
  63029. distanceModel: parsedSound.distanceModel,
  63030. playbackRate: parsedSound.playbackRate
  63031. };
  63032. var newSound;
  63033. if (!sourceSound) {
  63034. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63035. scene._addPendingData(newSound);
  63036. }
  63037. else {
  63038. var setBufferAndRun = function () {
  63039. if (sourceSound._isReadyToPlay) {
  63040. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63041. newSound._isReadyToPlay = true;
  63042. if (newSound.autoplay) {
  63043. newSound.play();
  63044. }
  63045. }
  63046. else {
  63047. window.setTimeout(setBufferAndRun, 300);
  63048. }
  63049. };
  63050. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63051. setBufferAndRun();
  63052. }
  63053. if (parsedSound.position) {
  63054. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63055. newSound.setPosition(soundPosition);
  63056. }
  63057. if (parsedSound.isDirectional) {
  63058. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63059. if (parsedSound.localDirectionToMesh) {
  63060. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63061. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63062. }
  63063. }
  63064. if (parsedSound.connectedMeshId) {
  63065. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63066. if (connectedMesh) {
  63067. newSound.attachToMesh(connectedMesh);
  63068. }
  63069. }
  63070. return newSound;
  63071. };
  63072. return Sound;
  63073. }());
  63074. BABYLON.Sound = Sound;
  63075. })(BABYLON || (BABYLON = {}));
  63076. //# sourceMappingURL=babylon.sound.js.map
  63077. var BABYLON;
  63078. (function (BABYLON) {
  63079. var SoundTrack = /** @class */ (function () {
  63080. function SoundTrack(scene, options) {
  63081. this.id = -1;
  63082. this._isMainTrack = false;
  63083. this._isInitialized = false;
  63084. this._scene = scene;
  63085. this.soundCollection = new Array();
  63086. this._options = options;
  63087. if (!this._isMainTrack) {
  63088. this._scene.soundTracks.push(this);
  63089. this.id = this._scene.soundTracks.length - 1;
  63090. }
  63091. }
  63092. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63093. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63094. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63095. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63096. if (this._options) {
  63097. if (this._options.volume) {
  63098. this._outputAudioNode.gain.value = this._options.volume;
  63099. }
  63100. if (this._options.mainTrack) {
  63101. this._isMainTrack = this._options.mainTrack;
  63102. }
  63103. }
  63104. this._isInitialized = true;
  63105. }
  63106. };
  63107. SoundTrack.prototype.dispose = function () {
  63108. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63109. if (this._connectedAnalyser) {
  63110. this._connectedAnalyser.stopDebugCanvas();
  63111. }
  63112. while (this.soundCollection.length) {
  63113. this.soundCollection[0].dispose();
  63114. }
  63115. if (this._outputAudioNode) {
  63116. this._outputAudioNode.disconnect();
  63117. }
  63118. this._outputAudioNode = null;
  63119. }
  63120. };
  63121. SoundTrack.prototype.AddSound = function (sound) {
  63122. if (!this._isInitialized) {
  63123. this._initializeSoundTrackAudioGraph();
  63124. }
  63125. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63126. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63127. }
  63128. if (sound.soundTrackId) {
  63129. if (sound.soundTrackId === -1) {
  63130. this._scene.mainSoundTrack.RemoveSound(sound);
  63131. }
  63132. else {
  63133. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63134. }
  63135. }
  63136. this.soundCollection.push(sound);
  63137. sound.soundTrackId = this.id;
  63138. };
  63139. SoundTrack.prototype.RemoveSound = function (sound) {
  63140. var index = this.soundCollection.indexOf(sound);
  63141. if (index !== -1) {
  63142. this.soundCollection.splice(index, 1);
  63143. }
  63144. };
  63145. SoundTrack.prototype.setVolume = function (newVolume) {
  63146. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63147. this._outputAudioNode.gain.value = newVolume;
  63148. }
  63149. };
  63150. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63151. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63152. for (var i = 0; i < this.soundCollection.length; i++) {
  63153. this.soundCollection[i].switchPanningModelToHRTF();
  63154. }
  63155. }
  63156. };
  63157. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63158. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63159. for (var i = 0; i < this.soundCollection.length; i++) {
  63160. this.soundCollection[i].switchPanningModelToEqualPower();
  63161. }
  63162. }
  63163. };
  63164. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63165. if (this._connectedAnalyser) {
  63166. this._connectedAnalyser.stopDebugCanvas();
  63167. }
  63168. this._connectedAnalyser = analyser;
  63169. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63170. this._outputAudioNode.disconnect();
  63171. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63172. }
  63173. };
  63174. return SoundTrack;
  63175. }());
  63176. BABYLON.SoundTrack = SoundTrack;
  63177. })(BABYLON || (BABYLON = {}));
  63178. //# sourceMappingURL=babylon.soundtrack.js.map
  63179. var BABYLON;
  63180. (function (BABYLON) {
  63181. /**
  63182. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63183. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63184. */
  63185. var Analyser = /** @class */ (function () {
  63186. /**
  63187. * Creates a new analyser
  63188. * @param scene defines hosting scene
  63189. */
  63190. function Analyser(scene) {
  63191. /**
  63192. * Gets or sets the smoothing
  63193. * @ignorenaming
  63194. */
  63195. this.SMOOTHING = 0.75;
  63196. /**
  63197. * Gets or sets the FFT table size
  63198. * @ignorenaming
  63199. */
  63200. this.FFT_SIZE = 512;
  63201. /**
  63202. * Gets or sets the bar graph amplitude
  63203. * @ignorenaming
  63204. */
  63205. this.BARGRAPHAMPLITUDE = 256;
  63206. /**
  63207. * Gets or sets the position of the debug canvas
  63208. * @ignorenaming
  63209. */
  63210. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63211. /**
  63212. * Gets or sets the debug canvas size
  63213. * @ignorenaming
  63214. */
  63215. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63216. this._scene = scene;
  63217. this._audioEngine = BABYLON.Engine.audioEngine;
  63218. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63219. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63220. this._webAudioAnalyser.minDecibels = -140;
  63221. this._webAudioAnalyser.maxDecibels = 0;
  63222. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63223. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63224. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63225. }
  63226. }
  63227. /**
  63228. * Get the number of data values you will have to play with for the visualization
  63229. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63230. * @returns a number
  63231. */
  63232. Analyser.prototype.getFrequencyBinCount = function () {
  63233. if (this._audioEngine.canUseWebAudio) {
  63234. return this._webAudioAnalyser.frequencyBinCount;
  63235. }
  63236. else {
  63237. return 0;
  63238. }
  63239. };
  63240. /**
  63241. * Gets the current frequency data as a byte array
  63242. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63243. * @returns a Uint8Array
  63244. */
  63245. Analyser.prototype.getByteFrequencyData = function () {
  63246. if (this._audioEngine.canUseWebAudio) {
  63247. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63248. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63249. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63250. }
  63251. return this._byteFreqs;
  63252. };
  63253. /**
  63254. * Gets the current waveform as a byte array
  63255. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63256. * @returns a Uint8Array
  63257. */
  63258. Analyser.prototype.getByteTimeDomainData = function () {
  63259. if (this._audioEngine.canUseWebAudio) {
  63260. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63261. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63262. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63263. }
  63264. return this._byteTime;
  63265. };
  63266. /**
  63267. * Gets the current frequency data as a float array
  63268. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63269. * @returns a Float32Array
  63270. */
  63271. Analyser.prototype.getFloatFrequencyData = function () {
  63272. if (this._audioEngine.canUseWebAudio) {
  63273. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63274. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63275. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63276. }
  63277. return this._floatFreqs;
  63278. };
  63279. /**
  63280. * Renders the debug canvas
  63281. */
  63282. Analyser.prototype.drawDebugCanvas = function () {
  63283. var _this = this;
  63284. if (this._audioEngine.canUseWebAudio) {
  63285. if (!this._debugCanvas) {
  63286. this._debugCanvas = document.createElement("canvas");
  63287. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63288. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63289. this._debugCanvas.style.position = "absolute";
  63290. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63291. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63292. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63293. document.body.appendChild(this._debugCanvas);
  63294. this._registerFunc = function () {
  63295. _this.drawDebugCanvas();
  63296. };
  63297. this._scene.registerBeforeRender(this._registerFunc);
  63298. }
  63299. if (this._registerFunc && this._debugCanvasContext) {
  63300. var workingArray = this.getByteFrequencyData();
  63301. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63302. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63303. // Draw the frequency domain chart.
  63304. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63305. var value = workingArray[i];
  63306. var percent = value / this.BARGRAPHAMPLITUDE;
  63307. var height = this.DEBUGCANVASSIZE.height * percent;
  63308. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63309. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63310. var hue = i / this.getFrequencyBinCount() * 360;
  63311. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63312. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63313. }
  63314. }
  63315. }
  63316. };
  63317. /**
  63318. * Stops rendering the debug canvas and removes it
  63319. */
  63320. Analyser.prototype.stopDebugCanvas = function () {
  63321. if (this._debugCanvas) {
  63322. if (this._registerFunc) {
  63323. this._scene.unregisterBeforeRender(this._registerFunc);
  63324. this._registerFunc = null;
  63325. }
  63326. document.body.removeChild(this._debugCanvas);
  63327. this._debugCanvas = null;
  63328. this._debugCanvasContext = null;
  63329. }
  63330. };
  63331. /**
  63332. * Connects two audio nodes
  63333. * @param inputAudioNode defines first node to connect
  63334. * @param outputAudioNode defines second node to connect
  63335. */
  63336. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63337. if (this._audioEngine.canUseWebAudio) {
  63338. inputAudioNode.connect(this._webAudioAnalyser);
  63339. this._webAudioAnalyser.connect(outputAudioNode);
  63340. }
  63341. };
  63342. /**
  63343. * Releases all associated resources
  63344. */
  63345. Analyser.prototype.dispose = function () {
  63346. if (this._audioEngine.canUseWebAudio) {
  63347. this._webAudioAnalyser.disconnect();
  63348. }
  63349. };
  63350. return Analyser;
  63351. }());
  63352. BABYLON.Analyser = Analyser;
  63353. })(BABYLON || (BABYLON = {}));
  63354. //# sourceMappingURL=babylon.analyser.js.map
  63355. var BABYLON;
  63356. (function (BABYLON) {
  63357. var CubeTexture = /** @class */ (function (_super) {
  63358. __extends(CubeTexture, _super);
  63359. /**
  63360. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63361. * as prefiltered data.
  63362. * @param rootUrl defines the url of the texture or the root name of the six images
  63363. * @param scene defines the scene the texture is attached to
  63364. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63365. * @param noMipmap defines if mipmaps should be created or not
  63366. * @param files defines the six files to load for the different faces
  63367. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63368. * @param onError defines a callback triggered in case of error during load
  63369. * @param format defines the internal format to use for the texture once loaded
  63370. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63371. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63372. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63373. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63374. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63375. * @return the cube texture
  63376. */
  63377. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63378. if (extensions === void 0) { extensions = null; }
  63379. if (noMipmap === void 0) { noMipmap = false; }
  63380. if (files === void 0) { files = null; }
  63381. if (onLoad === void 0) { onLoad = null; }
  63382. if (onError === void 0) { onError = null; }
  63383. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63384. if (prefiltered === void 0) { prefiltered = false; }
  63385. if (forcedExtension === void 0) { forcedExtension = null; }
  63386. if (createPolynomials === void 0) { createPolynomials = false; }
  63387. if (lodScale === void 0) { lodScale = 0.8; }
  63388. if (lodOffset === void 0) { lodOffset = 0; }
  63389. var _this = _super.call(this, scene) || this;
  63390. /**
  63391. * Gets or sets the center of the bounding box associated with the cube texture
  63392. * It must define where the camera used to render the texture was set
  63393. */
  63394. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63395. _this._rotationY = 0;
  63396. /** @hidden */
  63397. _this._prefiltered = false;
  63398. _this.name = rootUrl;
  63399. _this.url = rootUrl;
  63400. _this._noMipmap = noMipmap;
  63401. _this.hasAlpha = false;
  63402. _this._format = format;
  63403. _this.isCube = true;
  63404. _this._textureMatrix = BABYLON.Matrix.Identity();
  63405. _this._createPolynomials = createPolynomials;
  63406. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63407. if (!rootUrl && !files) {
  63408. return _this;
  63409. }
  63410. var lastDot = rootUrl.lastIndexOf(".");
  63411. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63412. var isDDS = (extension === ".dds");
  63413. var isEnv = (extension === ".env");
  63414. if (isEnv) {
  63415. _this.gammaSpace = false;
  63416. _this._prefiltered = false;
  63417. }
  63418. else {
  63419. _this._prefiltered = prefiltered;
  63420. if (prefiltered) {
  63421. _this.gammaSpace = false;
  63422. }
  63423. }
  63424. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63425. if (!files) {
  63426. if (!isEnv && !isDDS && !extensions) {
  63427. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63428. }
  63429. files = [];
  63430. if (extensions) {
  63431. for (var index = 0; index < extensions.length; index++) {
  63432. files.push(rootUrl + extensions[index]);
  63433. }
  63434. }
  63435. }
  63436. _this._files = files;
  63437. if (!_this._texture) {
  63438. if (!scene.useDelayedTextureLoading) {
  63439. if (prefiltered) {
  63440. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63441. }
  63442. else {
  63443. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63444. }
  63445. }
  63446. else {
  63447. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63448. }
  63449. }
  63450. else if (onLoad) {
  63451. if (_this._texture.isReady) {
  63452. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63453. }
  63454. else {
  63455. _this._texture.onLoadedObservable.add(onLoad);
  63456. }
  63457. }
  63458. return _this;
  63459. }
  63460. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63461. get: function () {
  63462. return this._boundingBoxSize;
  63463. },
  63464. /**
  63465. * Gets or sets the size of the bounding box associated with the cube texture
  63466. * When defined, the cubemap will switch to local mode
  63467. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63468. * @example https://www.babylonjs-playground.com/#RNASML
  63469. */
  63470. set: function (value) {
  63471. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63472. return;
  63473. }
  63474. this._boundingBoxSize = value;
  63475. var scene = this.getScene();
  63476. if (scene) {
  63477. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63478. }
  63479. },
  63480. enumerable: true,
  63481. configurable: true
  63482. });
  63483. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63484. /**
  63485. * Gets texture matrix rotation angle around Y axis radians.
  63486. */
  63487. get: function () {
  63488. return this._rotationY;
  63489. },
  63490. /**
  63491. * Sets texture matrix rotation angle around Y axis in radians.
  63492. */
  63493. set: function (value) {
  63494. this._rotationY = value;
  63495. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63496. },
  63497. enumerable: true,
  63498. configurable: true
  63499. });
  63500. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63501. var rootUrlKey = "";
  63502. files.forEach(function (url) { return rootUrlKey += url; });
  63503. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63504. };
  63505. /**
  63506. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63507. * @param url defines the url of the prefiltered texture
  63508. * @param scene defines the scene the texture is attached to
  63509. * @param forcedExtension defines the extension of the file if different from the url
  63510. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63511. * @return the prefiltered texture
  63512. */
  63513. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63514. if (forcedExtension === void 0) { forcedExtension = null; }
  63515. if (createPolynomials === void 0) { createPolynomials = true; }
  63516. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63517. };
  63518. // Methods
  63519. CubeTexture.prototype.delayLoad = function () {
  63520. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63521. return;
  63522. }
  63523. var scene = this.getScene();
  63524. if (!scene) {
  63525. return;
  63526. }
  63527. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63528. this._texture = this._getFromCache(this.url, this._noMipmap);
  63529. if (!this._texture) {
  63530. if (this._prefiltered) {
  63531. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63532. }
  63533. else {
  63534. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63535. }
  63536. }
  63537. };
  63538. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63539. return this._textureMatrix;
  63540. };
  63541. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63542. this._textureMatrix = value;
  63543. };
  63544. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63545. var texture = BABYLON.SerializationHelper.Parse(function () {
  63546. var prefiltered = false;
  63547. if (parsedTexture.prefiltered) {
  63548. prefiltered = parsedTexture.prefiltered;
  63549. }
  63550. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63551. }, parsedTexture, scene);
  63552. // Local Cubemaps
  63553. if (parsedTexture.boundingBoxPosition) {
  63554. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63555. }
  63556. if (parsedTexture.boundingBoxSize) {
  63557. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63558. }
  63559. // Animations
  63560. if (parsedTexture.animations) {
  63561. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63562. var parsedAnimation = parsedTexture.animations[animationIndex];
  63563. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63564. }
  63565. }
  63566. return texture;
  63567. };
  63568. CubeTexture.prototype.clone = function () {
  63569. var _this = this;
  63570. return BABYLON.SerializationHelper.Clone(function () {
  63571. var scene = _this.getScene();
  63572. if (!scene) {
  63573. return _this;
  63574. }
  63575. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63576. }, this);
  63577. };
  63578. __decorate([
  63579. BABYLON.serialize("rotationY")
  63580. ], CubeTexture.prototype, "_rotationY", void 0);
  63581. return CubeTexture;
  63582. }(BABYLON.BaseTexture));
  63583. BABYLON.CubeTexture = CubeTexture;
  63584. })(BABYLON || (BABYLON = {}));
  63585. //# sourceMappingURL=babylon.cubeTexture.js.map
  63586. var BABYLON;
  63587. (function (BABYLON) {
  63588. /**
  63589. * Raw cube texture where the raw buffers are passed in
  63590. */
  63591. var RawCubeTexture = /** @class */ (function (_super) {
  63592. __extends(RawCubeTexture, _super);
  63593. /**
  63594. * Creates a cube texture where the raw buffers are passed in.
  63595. * @param scene defines the scene the texture is attached to
  63596. * @param data defines the array of data to use to create each face
  63597. * @param size defines the size of the textures
  63598. * @param format defines the format of the data
  63599. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  63600. * @param generateMipMaps defines if the engine should generate the mip levels
  63601. * @param invertY defines if data must be stored with Y axis inverted
  63602. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  63603. * @param compression defines the compression used (null by default)
  63604. */
  63605. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  63606. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63607. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63608. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63609. if (invertY === void 0) { invertY = false; }
  63610. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63611. if (compression === void 0) { compression = null; }
  63612. var _this = _super.call(this, "", scene) || this;
  63613. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  63614. return _this;
  63615. }
  63616. /**
  63617. * Updates the raw cube texture.
  63618. * @param data defines the data to store
  63619. * @param format defines the data format
  63620. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  63621. * @param invertY defines if data must be stored with Y axis inverted
  63622. * @param compression defines the compression used (null by default)
  63623. * @param level defines which level of the texture to update
  63624. */
  63625. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  63626. if (compression === void 0) { compression = null; }
  63627. if (level === void 0) { level = 0; }
  63628. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  63629. };
  63630. /**
  63631. * Updates a raw cube texture with RGBD encoded data.
  63632. * @param data defines the array of data [mipmap][face] to use to create each face
  63633. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  63634. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63635. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63636. * @returns a promsie that resolves when the operation is complete
  63637. */
  63638. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  63639. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  63640. if (lodScale === void 0) { lodScale = 0.8; }
  63641. if (lodOffset === void 0) { lodOffset = 0; }
  63642. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  63643. };
  63644. /**
  63645. * Clones the raw cube texture.
  63646. * @return a new cube texture
  63647. */
  63648. RawCubeTexture.prototype.clone = function () {
  63649. var _this = this;
  63650. return BABYLON.SerializationHelper.Clone(function () {
  63651. var scene = _this.getScene();
  63652. var internalTexture = _this._texture;
  63653. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  63654. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  63655. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  63656. }
  63657. return texture;
  63658. }, this);
  63659. };
  63660. /** @hidden */
  63661. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  63662. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  63663. internalTexture._bufferViewArrayArray = data;
  63664. internalTexture._lodGenerationScale = lodScale;
  63665. internalTexture._lodGenerationOffset = lodOffset;
  63666. internalTexture._sphericalPolynomial = sphericalPolynomial;
  63667. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  63668. internalTexture.isReady = true;
  63669. });
  63670. };
  63671. return RawCubeTexture;
  63672. }(BABYLON.CubeTexture));
  63673. BABYLON.RawCubeTexture = RawCubeTexture;
  63674. })(BABYLON || (BABYLON = {}));
  63675. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  63676. var BABYLON;
  63677. (function (BABYLON) {
  63678. var RenderTargetTexture = /** @class */ (function (_super) {
  63679. __extends(RenderTargetTexture, _super);
  63680. /**
  63681. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63682. * or used a shadow, depth texture...
  63683. * @param name The friendly name of the texture
  63684. * @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)
  63685. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63686. * @param generateMipMaps True if mip maps need to be generated after render.
  63687. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63688. * @param type The type of the buffer in the RTT (int, half float, float...)
  63689. * @param isCube True if a cube texture needs to be created
  63690. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63691. * @param generateDepthBuffer True to generate a depth buffer
  63692. * @param generateStencilBuffer True to generate a stencil buffer
  63693. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63694. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  63695. */
  63696. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  63697. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63698. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63699. if (isCube === void 0) { isCube = false; }
  63700. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63701. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63702. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63703. if (isMulti === void 0) { isMulti = false; }
  63704. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63705. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63706. _this.isCube = isCube;
  63707. /**
  63708. * Use this list to define the list of mesh you want to render.
  63709. */
  63710. _this.renderList = new Array();
  63711. _this.renderParticles = true;
  63712. _this.renderSprites = false;
  63713. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63714. _this.ignoreCameraViewport = false;
  63715. // Events
  63716. /**
  63717. * An event triggered when the texture is unbind.
  63718. */
  63719. _this.onBeforeBindObservable = new BABYLON.Observable();
  63720. /**
  63721. * An event triggered when the texture is unbind.
  63722. */
  63723. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63724. /**
  63725. * An event triggered before rendering the texture
  63726. */
  63727. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63728. /**
  63729. * An event triggered after rendering the texture
  63730. */
  63731. _this.onAfterRenderObservable = new BABYLON.Observable();
  63732. /**
  63733. * An event triggered after the texture clear
  63734. */
  63735. _this.onClearObservable = new BABYLON.Observable();
  63736. _this._currentRefreshId = -1;
  63737. _this._refreshRate = 1;
  63738. _this._samples = 1;
  63739. /**
  63740. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63741. * It must define where the camera used to render the texture is set
  63742. */
  63743. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63744. scene = _this.getScene();
  63745. if (!scene) {
  63746. return _this;
  63747. }
  63748. _this._engine = scene.getEngine();
  63749. _this.name = name;
  63750. _this.isRenderTarget = true;
  63751. _this._initialSizeParameter = size;
  63752. _this._processSizeParameter(size);
  63753. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63754. });
  63755. _this._generateMipMaps = generateMipMaps ? true : false;
  63756. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63757. // Rendering groups
  63758. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63759. if (isMulti) {
  63760. return _this;
  63761. }
  63762. _this._renderTargetOptions = {
  63763. generateMipMaps: generateMipMaps,
  63764. type: type,
  63765. format: format,
  63766. samplingMode: samplingMode,
  63767. generateDepthBuffer: generateDepthBuffer,
  63768. generateStencilBuffer: generateStencilBuffer
  63769. };
  63770. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63771. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63772. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63773. }
  63774. if (isCube) {
  63775. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63776. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63777. _this._textureMatrix = BABYLON.Matrix.Identity();
  63778. }
  63779. else {
  63780. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63781. }
  63782. return _this;
  63783. }
  63784. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63785. get: function () {
  63786. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63787. },
  63788. enumerable: true,
  63789. configurable: true
  63790. });
  63791. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63792. get: function () {
  63793. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63794. },
  63795. enumerable: true,
  63796. configurable: true
  63797. });
  63798. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63799. get: function () {
  63800. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63801. },
  63802. enumerable: true,
  63803. configurable: true
  63804. });
  63805. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63806. set: function (callback) {
  63807. if (this._onAfterUnbindObserver) {
  63808. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63809. }
  63810. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63811. },
  63812. enumerable: true,
  63813. configurable: true
  63814. });
  63815. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63816. set: function (callback) {
  63817. if (this._onBeforeRenderObserver) {
  63818. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63819. }
  63820. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63821. },
  63822. enumerable: true,
  63823. configurable: true
  63824. });
  63825. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63826. set: function (callback) {
  63827. if (this._onAfterRenderObserver) {
  63828. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63829. }
  63830. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63831. },
  63832. enumerable: true,
  63833. configurable: true
  63834. });
  63835. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63836. set: function (callback) {
  63837. if (this._onClearObserver) {
  63838. this.onClearObservable.remove(this._onClearObserver);
  63839. }
  63840. this._onClearObserver = this.onClearObservable.add(callback);
  63841. },
  63842. enumerable: true,
  63843. configurable: true
  63844. });
  63845. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63846. get: function () {
  63847. return this._renderTargetOptions;
  63848. },
  63849. enumerable: true,
  63850. configurable: true
  63851. });
  63852. RenderTargetTexture.prototype._onRatioRescale = function () {
  63853. if (this._sizeRatio) {
  63854. this.resize(this._initialSizeParameter);
  63855. }
  63856. };
  63857. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63858. get: function () {
  63859. return this._boundingBoxSize;
  63860. },
  63861. /**
  63862. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63863. * When defined, the cubemap will switch to local mode
  63864. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63865. * @example https://www.babylonjs-playground.com/#RNASML
  63866. */
  63867. set: function (value) {
  63868. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63869. return;
  63870. }
  63871. this._boundingBoxSize = value;
  63872. var scene = this.getScene();
  63873. if (scene) {
  63874. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63875. }
  63876. },
  63877. enumerable: true,
  63878. configurable: true
  63879. });
  63880. /**
  63881. * Creates a depth stencil texture.
  63882. * This is only available in WebGL 2 or with the depth texture extension available.
  63883. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63884. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63885. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63886. */
  63887. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63888. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63889. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63890. if (generateStencil === void 0) { generateStencil = false; }
  63891. if (!this.getScene()) {
  63892. return;
  63893. }
  63894. var engine = this.getScene().getEngine();
  63895. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63896. bilinearFiltering: bilinearFiltering,
  63897. comparisonFunction: comparisonFunction,
  63898. generateStencil: generateStencil,
  63899. isCube: this.isCube
  63900. });
  63901. engine.setFrameBufferDepthStencilTexture(this);
  63902. };
  63903. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63904. if (size.ratio) {
  63905. this._sizeRatio = size.ratio;
  63906. this._size = {
  63907. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63908. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63909. };
  63910. }
  63911. else {
  63912. this._size = size;
  63913. }
  63914. };
  63915. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63916. get: function () {
  63917. return this._samples;
  63918. },
  63919. set: function (value) {
  63920. if (this._samples === value) {
  63921. return;
  63922. }
  63923. var scene = this.getScene();
  63924. if (!scene) {
  63925. return;
  63926. }
  63927. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63928. },
  63929. enumerable: true,
  63930. configurable: true
  63931. });
  63932. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63933. this._currentRefreshId = -1;
  63934. };
  63935. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63936. get: function () {
  63937. return this._refreshRate;
  63938. },
  63939. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63940. set: function (value) {
  63941. this._refreshRate = value;
  63942. this.resetRefreshCounter();
  63943. },
  63944. enumerable: true,
  63945. configurable: true
  63946. });
  63947. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63948. if (!this._postProcessManager) {
  63949. var scene = this.getScene();
  63950. if (!scene) {
  63951. return;
  63952. }
  63953. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63954. this._postProcesses = new Array();
  63955. }
  63956. this._postProcesses.push(postProcess);
  63957. this._postProcesses[0].autoClear = false;
  63958. };
  63959. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63960. if (!this._postProcesses) {
  63961. return;
  63962. }
  63963. if (dispose) {
  63964. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63965. var postProcess = _a[_i];
  63966. postProcess.dispose();
  63967. }
  63968. }
  63969. this._postProcesses = [];
  63970. };
  63971. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63972. if (!this._postProcesses) {
  63973. return;
  63974. }
  63975. var index = this._postProcesses.indexOf(postProcess);
  63976. if (index === -1) {
  63977. return;
  63978. }
  63979. this._postProcesses.splice(index, 1);
  63980. if (this._postProcesses.length > 0) {
  63981. this._postProcesses[0].autoClear = false;
  63982. }
  63983. };
  63984. RenderTargetTexture.prototype._shouldRender = function () {
  63985. if (this._currentRefreshId === -1) { // At least render once
  63986. this._currentRefreshId = 1;
  63987. return true;
  63988. }
  63989. if (this.refreshRate === this._currentRefreshId) {
  63990. this._currentRefreshId = 1;
  63991. return true;
  63992. }
  63993. this._currentRefreshId++;
  63994. return false;
  63995. };
  63996. RenderTargetTexture.prototype.getRenderSize = function () {
  63997. if (this._size.width) {
  63998. return this._size.width;
  63999. }
  64000. return this._size;
  64001. };
  64002. RenderTargetTexture.prototype.getRenderWidth = function () {
  64003. if (this._size.width) {
  64004. return this._size.width;
  64005. }
  64006. return this._size;
  64007. };
  64008. RenderTargetTexture.prototype.getRenderHeight = function () {
  64009. if (this._size.width) {
  64010. return this._size.height;
  64011. }
  64012. return this._size;
  64013. };
  64014. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  64015. get: function () {
  64016. return true;
  64017. },
  64018. enumerable: true,
  64019. configurable: true
  64020. });
  64021. RenderTargetTexture.prototype.scale = function (ratio) {
  64022. var newSize = this.getRenderSize() * ratio;
  64023. this.resize(newSize);
  64024. };
  64025. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  64026. if (this.isCube) {
  64027. return this._textureMatrix;
  64028. }
  64029. return _super.prototype.getReflectionTextureMatrix.call(this);
  64030. };
  64031. RenderTargetTexture.prototype.resize = function (size) {
  64032. this.releaseInternalTexture();
  64033. var scene = this.getScene();
  64034. if (!scene) {
  64035. return;
  64036. }
  64037. this._processSizeParameter(size);
  64038. if (this.isCube) {
  64039. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64040. }
  64041. else {
  64042. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64043. }
  64044. };
  64045. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64046. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64047. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64048. var scene = this.getScene();
  64049. if (!scene) {
  64050. return;
  64051. }
  64052. var engine = scene.getEngine();
  64053. if (this.useCameraPostProcesses !== undefined) {
  64054. useCameraPostProcess = this.useCameraPostProcesses;
  64055. }
  64056. if (this._waitingRenderList) {
  64057. this.renderList = [];
  64058. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64059. var id = this._waitingRenderList[index];
  64060. var mesh_1 = scene.getMeshByID(id);
  64061. if (mesh_1) {
  64062. this.renderList.push(mesh_1);
  64063. }
  64064. }
  64065. delete this._waitingRenderList;
  64066. }
  64067. // Is predicate defined?
  64068. if (this.renderListPredicate) {
  64069. if (this.renderList) {
  64070. this.renderList.splice(0); // Clear previous renderList
  64071. }
  64072. else {
  64073. this.renderList = [];
  64074. }
  64075. var scene = this.getScene();
  64076. if (!scene) {
  64077. return;
  64078. }
  64079. var sceneMeshes = scene.meshes;
  64080. for (var index = 0; index < sceneMeshes.length; index++) {
  64081. var mesh = sceneMeshes[index];
  64082. if (this.renderListPredicate(mesh)) {
  64083. this.renderList.push(mesh);
  64084. }
  64085. }
  64086. }
  64087. this.onBeforeBindObservable.notifyObservers(this);
  64088. // Set custom projection.
  64089. // Needs to be before binding to prevent changing the aspect ratio.
  64090. var camera;
  64091. if (this.activeCamera) {
  64092. camera = this.activeCamera;
  64093. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64094. if (this.activeCamera !== scene.activeCamera) {
  64095. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64096. }
  64097. }
  64098. else {
  64099. camera = scene.activeCamera;
  64100. if (camera) {
  64101. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64102. }
  64103. }
  64104. // Prepare renderingManager
  64105. this._renderingManager.reset();
  64106. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64107. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64108. var sceneRenderId = scene.getRenderId();
  64109. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64110. var mesh = currentRenderList[meshIndex];
  64111. if (mesh) {
  64112. if (!mesh.isReady(this.refreshRate === 0)) {
  64113. this.resetRefreshCounter();
  64114. continue;
  64115. }
  64116. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64117. var isMasked = void 0;
  64118. if (!this.renderList && camera) {
  64119. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64120. }
  64121. else {
  64122. isMasked = false;
  64123. }
  64124. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64125. mesh._activate(sceneRenderId);
  64126. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64127. var subMesh = mesh.subMeshes[subIndex];
  64128. scene._activeIndices.addCount(subMesh.indexCount, false);
  64129. this._renderingManager.dispatch(subMesh, mesh);
  64130. }
  64131. }
  64132. }
  64133. }
  64134. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64135. var particleSystem = scene.particleSystems[particleIndex];
  64136. var emitter = particleSystem.emitter;
  64137. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64138. continue;
  64139. }
  64140. if (currentRenderList.indexOf(emitter) >= 0) {
  64141. this._renderingManager.dispatchParticles(particleSystem);
  64142. }
  64143. }
  64144. if (this.isCube) {
  64145. for (var face = 0; face < 6; face++) {
  64146. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64147. scene.incrementRenderId();
  64148. scene.resetCachedMaterial();
  64149. }
  64150. }
  64151. else {
  64152. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64153. }
  64154. this.onAfterUnbindObservable.notifyObservers(this);
  64155. if (scene.activeCamera) {
  64156. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64157. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64158. }
  64159. engine.setViewport(scene.activeCamera.viewport);
  64160. }
  64161. scene.resetCachedMaterial();
  64162. };
  64163. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64164. var minimum = 128;
  64165. var x = renderDimension * scale;
  64166. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64167. // Ensure we don't exceed the render dimension (while staying POT)
  64168. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64169. };
  64170. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64171. var _this = this;
  64172. if (!this._texture) {
  64173. return;
  64174. }
  64175. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64176. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64177. });
  64178. };
  64179. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64180. var scene = this.getScene();
  64181. if (!scene) {
  64182. return;
  64183. }
  64184. var engine = scene.getEngine();
  64185. if (!this._texture) {
  64186. return;
  64187. }
  64188. // Bind
  64189. if (this._postProcessManager) {
  64190. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64191. }
  64192. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64193. if (this._texture) {
  64194. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64195. }
  64196. }
  64197. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64198. // Clear
  64199. if (this.onClearObservable.hasObservers()) {
  64200. this.onClearObservable.notifyObservers(engine);
  64201. }
  64202. else {
  64203. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64204. }
  64205. if (!this._doNotChangeAspectRatio) {
  64206. scene.updateTransformMatrix(true);
  64207. }
  64208. // Render
  64209. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64210. if (this._postProcessManager) {
  64211. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64212. }
  64213. else if (useCameraPostProcess) {
  64214. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64215. }
  64216. if (!this._doNotChangeAspectRatio) {
  64217. scene.updateTransformMatrix(true);
  64218. }
  64219. // Dump ?
  64220. if (dumpForDebug) {
  64221. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64222. }
  64223. // Unbind
  64224. if (!this.isCube || faceIndex === 5) {
  64225. if (this.isCube) {
  64226. if (faceIndex === 5) {
  64227. engine.generateMipMapsForCubemap(this._texture);
  64228. }
  64229. }
  64230. this.unbindFrameBuffer(engine, faceIndex);
  64231. }
  64232. else {
  64233. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64234. }
  64235. };
  64236. /**
  64237. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64238. * This allowed control for front to back rendering or reversly depending of the special needs.
  64239. *
  64240. * @param renderingGroupId The rendering group id corresponding to its index
  64241. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64242. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64243. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64244. */
  64245. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64246. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64247. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64248. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64249. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64250. };
  64251. /**
  64252. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64253. *
  64254. * @param renderingGroupId The rendering group id corresponding to its index
  64255. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64256. */
  64257. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64258. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64259. };
  64260. RenderTargetTexture.prototype.clone = function () {
  64261. var textureSize = this.getSize();
  64262. 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);
  64263. // Base texture
  64264. newTexture.hasAlpha = this.hasAlpha;
  64265. newTexture.level = this.level;
  64266. // RenderTarget Texture
  64267. newTexture.coordinatesMode = this.coordinatesMode;
  64268. if (this.renderList) {
  64269. newTexture.renderList = this.renderList.slice(0);
  64270. }
  64271. return newTexture;
  64272. };
  64273. RenderTargetTexture.prototype.serialize = function () {
  64274. if (!this.name) {
  64275. return null;
  64276. }
  64277. var serializationObject = _super.prototype.serialize.call(this);
  64278. serializationObject.renderTargetSize = this.getRenderSize();
  64279. serializationObject.renderList = [];
  64280. if (this.renderList) {
  64281. for (var index = 0; index < this.renderList.length; index++) {
  64282. serializationObject.renderList.push(this.renderList[index].id);
  64283. }
  64284. }
  64285. return serializationObject;
  64286. };
  64287. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64288. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64289. var objBuffer = this.getInternalTexture();
  64290. var scene = this.getScene();
  64291. if (objBuffer && scene) {
  64292. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64293. }
  64294. };
  64295. RenderTargetTexture.prototype.dispose = function () {
  64296. if (this._postProcessManager) {
  64297. this._postProcessManager.dispose();
  64298. this._postProcessManager = null;
  64299. }
  64300. this.clearPostProcesses(true);
  64301. if (this._resizeObserver) {
  64302. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64303. this._resizeObserver = null;
  64304. }
  64305. this.renderList = null;
  64306. // Remove from custom render targets
  64307. var scene = this.getScene();
  64308. if (!scene) {
  64309. return;
  64310. }
  64311. var index = scene.customRenderTargets.indexOf(this);
  64312. if (index >= 0) {
  64313. scene.customRenderTargets.splice(index, 1);
  64314. }
  64315. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64316. var camera = _a[_i];
  64317. index = camera.customRenderTargets.indexOf(this);
  64318. if (index >= 0) {
  64319. camera.customRenderTargets.splice(index, 1);
  64320. }
  64321. }
  64322. _super.prototype.dispose.call(this);
  64323. };
  64324. RenderTargetTexture.prototype._rebuild = function () {
  64325. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64326. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64327. }
  64328. if (this._postProcessManager) {
  64329. this._postProcessManager._rebuild();
  64330. }
  64331. };
  64332. /**
  64333. * Clear the info related to rendering groups preventing retention point in material dispose.
  64334. */
  64335. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64336. if (this._renderingManager) {
  64337. this._renderingManager.freeRenderingGroups();
  64338. }
  64339. };
  64340. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64341. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64342. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64343. return RenderTargetTexture;
  64344. }(BABYLON.Texture));
  64345. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64346. })(BABYLON || (BABYLON = {}));
  64347. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64348. var BABYLON;
  64349. (function (BABYLON) {
  64350. ;
  64351. var MultiRenderTarget = /** @class */ (function (_super) {
  64352. __extends(MultiRenderTarget, _super);
  64353. function MultiRenderTarget(name, size, count, scene, options) {
  64354. var _this = this;
  64355. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64356. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64357. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64358. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64359. _this._engine = scene.getEngine();
  64360. if (!_this.isSupported) {
  64361. _this.dispose();
  64362. return;
  64363. }
  64364. var types = [];
  64365. var samplingModes = [];
  64366. for (var i = 0; i < count; i++) {
  64367. if (options && options.types && options.types[i] !== undefined) {
  64368. types.push(options.types[i]);
  64369. }
  64370. else {
  64371. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64372. }
  64373. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64374. samplingModes.push(options.samplingModes[i]);
  64375. }
  64376. else {
  64377. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64378. }
  64379. }
  64380. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64381. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64382. _this._size = size;
  64383. _this._multiRenderTargetOptions = {
  64384. samplingModes: samplingModes,
  64385. generateMipMaps: generateMipMaps,
  64386. generateDepthBuffer: generateDepthBuffer,
  64387. generateStencilBuffer: generateStencilBuffer,
  64388. generateDepthTexture: generateDepthTexture,
  64389. types: types,
  64390. textureCount: count
  64391. };
  64392. _this._createInternalTextures();
  64393. _this._createTextures();
  64394. return _this;
  64395. }
  64396. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64397. get: function () {
  64398. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64399. },
  64400. enumerable: true,
  64401. configurable: true
  64402. });
  64403. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64404. get: function () {
  64405. return this._textures;
  64406. },
  64407. enumerable: true,
  64408. configurable: true
  64409. });
  64410. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64411. get: function () {
  64412. return this._textures[this._textures.length - 1];
  64413. },
  64414. enumerable: true,
  64415. configurable: true
  64416. });
  64417. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64418. set: function (wrap) {
  64419. if (this._textures) {
  64420. for (var i = 0; i < this._textures.length; i++) {
  64421. this._textures[i].wrapU = wrap;
  64422. }
  64423. }
  64424. },
  64425. enumerable: true,
  64426. configurable: true
  64427. });
  64428. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64429. set: function (wrap) {
  64430. if (this._textures) {
  64431. for (var i = 0; i < this._textures.length; i++) {
  64432. this._textures[i].wrapV = wrap;
  64433. }
  64434. }
  64435. },
  64436. enumerable: true,
  64437. configurable: true
  64438. });
  64439. MultiRenderTarget.prototype._rebuild = function () {
  64440. this.releaseInternalTextures();
  64441. this._createInternalTextures();
  64442. for (var i = 0; i < this._internalTextures.length; i++) {
  64443. var texture = this._textures[i];
  64444. texture._texture = this._internalTextures[i];
  64445. }
  64446. // Keeps references to frame buffer and stencil/depth buffer
  64447. this._texture = this._internalTextures[0];
  64448. };
  64449. MultiRenderTarget.prototype._createInternalTextures = function () {
  64450. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64451. };
  64452. MultiRenderTarget.prototype._createTextures = function () {
  64453. this._textures = [];
  64454. for (var i = 0; i < this._internalTextures.length; i++) {
  64455. var texture = new BABYLON.Texture(null, this.getScene());
  64456. texture._texture = this._internalTextures[i];
  64457. this._textures.push(texture);
  64458. }
  64459. // Keeps references to frame buffer and stencil/depth buffer
  64460. this._texture = this._internalTextures[0];
  64461. };
  64462. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64463. get: function () {
  64464. return this._samples;
  64465. },
  64466. set: function (value) {
  64467. if (this._samples === value) {
  64468. return;
  64469. }
  64470. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64471. },
  64472. enumerable: true,
  64473. configurable: true
  64474. });
  64475. MultiRenderTarget.prototype.resize = function (size) {
  64476. this.releaseInternalTextures();
  64477. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64478. this._createInternalTextures();
  64479. };
  64480. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64481. var _this = this;
  64482. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64483. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64484. });
  64485. };
  64486. MultiRenderTarget.prototype.dispose = function () {
  64487. this.releaseInternalTextures();
  64488. _super.prototype.dispose.call(this);
  64489. };
  64490. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64491. if (!this._internalTextures) {
  64492. return;
  64493. }
  64494. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64495. if (this._internalTextures[i] !== undefined) {
  64496. this._internalTextures[i].dispose();
  64497. this._internalTextures.splice(i, 1);
  64498. }
  64499. }
  64500. };
  64501. return MultiRenderTarget;
  64502. }(BABYLON.RenderTargetTexture));
  64503. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64504. })(BABYLON || (BABYLON = {}));
  64505. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64506. var BABYLON;
  64507. (function (BABYLON) {
  64508. var MirrorTexture = /** @class */ (function (_super) {
  64509. __extends(MirrorTexture, _super);
  64510. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64511. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64512. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64513. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64514. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64515. _this.scene = scene;
  64516. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64517. _this._transformMatrix = BABYLON.Matrix.Zero();
  64518. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64519. _this._adaptiveBlurKernel = 0;
  64520. _this._blurKernelX = 0;
  64521. _this._blurKernelY = 0;
  64522. _this._blurRatio = 1.0;
  64523. _this.ignoreCameraViewport = true;
  64524. _this._updateGammaSpace();
  64525. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64526. _this._updateGammaSpace;
  64527. });
  64528. _this.onBeforeRenderObservable.add(function () {
  64529. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64530. _this._savedViewMatrix = scene.getViewMatrix();
  64531. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64532. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64533. scene.clipPlane = _this.mirrorPlane;
  64534. scene.getEngine().cullBackFaces = false;
  64535. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64536. });
  64537. _this.onAfterRenderObservable.add(function () {
  64538. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64539. scene.getEngine().cullBackFaces = true;
  64540. scene._mirroredCameraPosition = null;
  64541. delete scene.clipPlane;
  64542. });
  64543. return _this;
  64544. }
  64545. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64546. get: function () {
  64547. return this._blurRatio;
  64548. },
  64549. set: function (value) {
  64550. if (this._blurRatio === value) {
  64551. return;
  64552. }
  64553. this._blurRatio = value;
  64554. this._preparePostProcesses();
  64555. },
  64556. enumerable: true,
  64557. configurable: true
  64558. });
  64559. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64560. set: function (value) {
  64561. this._adaptiveBlurKernel = value;
  64562. this._autoComputeBlurKernel();
  64563. },
  64564. enumerable: true,
  64565. configurable: true
  64566. });
  64567. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64568. set: function (value) {
  64569. this.blurKernelX = value;
  64570. this.blurKernelY = value;
  64571. },
  64572. enumerable: true,
  64573. configurable: true
  64574. });
  64575. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64576. get: function () {
  64577. return this._blurKernelX;
  64578. },
  64579. set: function (value) {
  64580. if (this._blurKernelX === value) {
  64581. return;
  64582. }
  64583. this._blurKernelX = value;
  64584. this._preparePostProcesses();
  64585. },
  64586. enumerable: true,
  64587. configurable: true
  64588. });
  64589. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64590. get: function () {
  64591. return this._blurKernelY;
  64592. },
  64593. set: function (value) {
  64594. if (this._blurKernelY === value) {
  64595. return;
  64596. }
  64597. this._blurKernelY = value;
  64598. this._preparePostProcesses();
  64599. },
  64600. enumerable: true,
  64601. configurable: true
  64602. });
  64603. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64604. var engine = this.getScene().getEngine();
  64605. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64606. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64607. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64608. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64609. };
  64610. MirrorTexture.prototype._onRatioRescale = function () {
  64611. if (this._sizeRatio) {
  64612. this.resize(this._initialSizeParameter);
  64613. if (!this._adaptiveBlurKernel) {
  64614. this._preparePostProcesses();
  64615. }
  64616. }
  64617. if (this._adaptiveBlurKernel) {
  64618. this._autoComputeBlurKernel();
  64619. }
  64620. };
  64621. MirrorTexture.prototype._updateGammaSpace = function () {
  64622. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64623. };
  64624. MirrorTexture.prototype._preparePostProcesses = function () {
  64625. this.clearPostProcesses(true);
  64626. if (this._blurKernelX && this._blurKernelY) {
  64627. var engine = this.getScene().getEngine();
  64628. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64629. 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);
  64630. this._blurX.autoClear = false;
  64631. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64632. this._blurX.inputTexture = this._texture;
  64633. }
  64634. else {
  64635. this._blurX.alwaysForcePOT = true;
  64636. }
  64637. 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);
  64638. this._blurY.autoClear = false;
  64639. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64640. this.addPostProcess(this._blurX);
  64641. this.addPostProcess(this._blurY);
  64642. }
  64643. else {
  64644. if (this._blurY) {
  64645. this.removePostProcess(this._blurY);
  64646. this._blurY.dispose();
  64647. this._blurY = null;
  64648. }
  64649. if (this._blurX) {
  64650. this.removePostProcess(this._blurX);
  64651. this._blurX.dispose();
  64652. this._blurX = null;
  64653. }
  64654. }
  64655. };
  64656. MirrorTexture.prototype.clone = function () {
  64657. var scene = this.getScene();
  64658. if (!scene) {
  64659. return this;
  64660. }
  64661. var textureSize = this.getSize();
  64662. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64663. // Base texture
  64664. newTexture.hasAlpha = this.hasAlpha;
  64665. newTexture.level = this.level;
  64666. // Mirror Texture
  64667. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64668. if (this.renderList) {
  64669. newTexture.renderList = this.renderList.slice(0);
  64670. }
  64671. return newTexture;
  64672. };
  64673. MirrorTexture.prototype.serialize = function () {
  64674. if (!this.name) {
  64675. return null;
  64676. }
  64677. var serializationObject = _super.prototype.serialize.call(this);
  64678. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64679. return serializationObject;
  64680. };
  64681. MirrorTexture.prototype.dispose = function () {
  64682. _super.prototype.dispose.call(this);
  64683. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64684. };
  64685. return MirrorTexture;
  64686. }(BABYLON.RenderTargetTexture));
  64687. BABYLON.MirrorTexture = MirrorTexture;
  64688. })(BABYLON || (BABYLON = {}));
  64689. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64690. var BABYLON;
  64691. (function (BABYLON) {
  64692. /**
  64693. * Creates a refraction texture used by refraction channel of the standard material.
  64694. * @param name the texture name
  64695. * @param size size of the underlying texture
  64696. * @param scene root scene
  64697. */
  64698. var RefractionTexture = /** @class */ (function (_super) {
  64699. __extends(RefractionTexture, _super);
  64700. function RefractionTexture(name, size, scene, generateMipMaps) {
  64701. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64702. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64703. _this.depth = 2.0;
  64704. _this.onBeforeRenderObservable.add(function () {
  64705. scene.clipPlane = _this.refractionPlane;
  64706. });
  64707. _this.onAfterRenderObservable.add(function () {
  64708. delete scene.clipPlane;
  64709. });
  64710. return _this;
  64711. }
  64712. RefractionTexture.prototype.clone = function () {
  64713. var scene = this.getScene();
  64714. if (!scene) {
  64715. return this;
  64716. }
  64717. var textureSize = this.getSize();
  64718. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64719. // Base texture
  64720. newTexture.hasAlpha = this.hasAlpha;
  64721. newTexture.level = this.level;
  64722. // Refraction Texture
  64723. newTexture.refractionPlane = this.refractionPlane.clone();
  64724. if (this.renderList) {
  64725. newTexture.renderList = this.renderList.slice(0);
  64726. }
  64727. newTexture.depth = this.depth;
  64728. return newTexture;
  64729. };
  64730. RefractionTexture.prototype.serialize = function () {
  64731. if (!this.name) {
  64732. return null;
  64733. }
  64734. var serializationObject = _super.prototype.serialize.call(this);
  64735. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64736. serializationObject.depth = this.depth;
  64737. return serializationObject;
  64738. };
  64739. return RefractionTexture;
  64740. }(BABYLON.RenderTargetTexture));
  64741. BABYLON.RefractionTexture = RefractionTexture;
  64742. })(BABYLON || (BABYLON = {}));
  64743. //# sourceMappingURL=babylon.refractionTexture.js.map
  64744. var BABYLON;
  64745. (function (BABYLON) {
  64746. /**
  64747. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64748. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64749. */
  64750. var DynamicTexture = /** @class */ (function (_super) {
  64751. __extends(DynamicTexture, _super);
  64752. /**
  64753. * Creates a {BABYLON.DynamicTexture}
  64754. * @param name defines the name of the texture
  64755. * @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
  64756. * @param scene defines the scene where you want the texture
  64757. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64758. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64759. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64760. */
  64761. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64762. if (scene === void 0) { scene = null; }
  64763. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64764. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64765. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64766. _this.name = name;
  64767. _this._engine = _this.getScene().getEngine();
  64768. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64769. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64770. _this._generateMipMaps = generateMipMaps;
  64771. if (options.getContext) {
  64772. _this._canvas = options;
  64773. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64774. }
  64775. else {
  64776. _this._canvas = document.createElement("canvas");
  64777. if (options.width || options.width === 0) {
  64778. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64779. }
  64780. else {
  64781. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64782. }
  64783. }
  64784. var textureSize = _this.getSize();
  64785. _this._canvas.width = textureSize.width;
  64786. _this._canvas.height = textureSize.height;
  64787. _this._context = _this._canvas.getContext("2d");
  64788. return _this;
  64789. }
  64790. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64791. /**
  64792. * Gets the current state of canRescale
  64793. */
  64794. get: function () {
  64795. return true;
  64796. },
  64797. enumerable: true,
  64798. configurable: true
  64799. });
  64800. DynamicTexture.prototype._recreate = function (textureSize) {
  64801. this._canvas.width = textureSize.width;
  64802. this._canvas.height = textureSize.height;
  64803. this.releaseInternalTexture();
  64804. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64805. };
  64806. /**
  64807. * Scales the texture
  64808. * @param ratio the scale factor to apply to both width and height
  64809. */
  64810. DynamicTexture.prototype.scale = function (ratio) {
  64811. var textureSize = this.getSize();
  64812. textureSize.width *= ratio;
  64813. textureSize.height *= ratio;
  64814. this._recreate(textureSize);
  64815. };
  64816. /**
  64817. * Resizes the texture
  64818. * @param width the new width
  64819. * @param height the new height
  64820. */
  64821. DynamicTexture.prototype.scaleTo = function (width, height) {
  64822. var textureSize = this.getSize();
  64823. textureSize.width = width;
  64824. textureSize.height = height;
  64825. this._recreate(textureSize);
  64826. };
  64827. /**
  64828. * Gets the context of the canvas used by the texture
  64829. * @returns the canvas context of the dynamic texture
  64830. */
  64831. DynamicTexture.prototype.getContext = function () {
  64832. return this._context;
  64833. };
  64834. /**
  64835. * Clears the texture
  64836. */
  64837. DynamicTexture.prototype.clear = function () {
  64838. var size = this.getSize();
  64839. this._context.fillRect(0, 0, size.width, size.height);
  64840. };
  64841. /**
  64842. * Updates the texture
  64843. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64844. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64845. */
  64846. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64847. if (premulAlpha === void 0) { premulAlpha = false; }
  64848. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64849. };
  64850. /**
  64851. * Draws text onto the texture
  64852. * @param text defines the text to be drawn
  64853. * @param x defines the placement of the text from the left
  64854. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64855. * @param font defines the font to be used with font-style, font-size, font-name
  64856. * @param color defines the color used for the text
  64857. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64858. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64859. * @param update defines whether texture is immediately update (default is true)
  64860. */
  64861. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64862. if (update === void 0) { update = true; }
  64863. var size = this.getSize();
  64864. if (clearColor) {
  64865. this._context.fillStyle = clearColor;
  64866. this._context.fillRect(0, 0, size.width, size.height);
  64867. }
  64868. this._context.font = font;
  64869. if (x === null || x === undefined) {
  64870. var textSize = this._context.measureText(text);
  64871. x = (size.width - textSize.width) / 2;
  64872. }
  64873. if (y === null || y === undefined) {
  64874. var fontSize = parseInt((font.replace(/\D/g, '')));
  64875. y = (size.height / 2) + (fontSize / 3.65);
  64876. }
  64877. this._context.fillStyle = color;
  64878. this._context.fillText(text, x, y);
  64879. if (update) {
  64880. this.update(invertY);
  64881. }
  64882. };
  64883. /**
  64884. * Clones the texture
  64885. * @returns the clone of the texture.
  64886. */
  64887. DynamicTexture.prototype.clone = function () {
  64888. var scene = this.getScene();
  64889. if (!scene) {
  64890. return this;
  64891. }
  64892. var textureSize = this.getSize();
  64893. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64894. // Base texture
  64895. newTexture.hasAlpha = this.hasAlpha;
  64896. newTexture.level = this.level;
  64897. // Dynamic Texture
  64898. newTexture.wrapU = this.wrapU;
  64899. newTexture.wrapV = this.wrapV;
  64900. return newTexture;
  64901. };
  64902. /** @hidden */
  64903. DynamicTexture.prototype._rebuild = function () {
  64904. this.update();
  64905. };
  64906. return DynamicTexture;
  64907. }(BABYLON.Texture));
  64908. BABYLON.DynamicTexture = DynamicTexture;
  64909. })(BABYLON || (BABYLON = {}));
  64910. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64911. var BABYLON;
  64912. (function (BABYLON) {
  64913. var VideoTexture = /** @class */ (function (_super) {
  64914. __extends(VideoTexture, _super);
  64915. /**
  64916. * Creates a video texture.
  64917. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64918. * @param {string | null} name optional name, will detect from video source, if not defined
  64919. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64920. * @param {BABYLON.Scene} scene is obviously the current scene.
  64921. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64922. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64923. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64924. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64925. */
  64926. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64927. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64928. if (invertY === void 0) { invertY = false; }
  64929. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64930. if (settings === void 0) { settings = {
  64931. autoPlay: true,
  64932. loop: true,
  64933. autoUpdateTexture: true,
  64934. }; }
  64935. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64936. _this._onUserActionRequestedObservable = null;
  64937. _this._stillImageCaptured = false;
  64938. _this._createInternalTexture = function () {
  64939. if (_this._texture != null) {
  64940. return;
  64941. }
  64942. if (!_this._engine.needPOTTextures ||
  64943. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64944. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64945. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64946. }
  64947. else {
  64948. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64949. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64950. _this._generateMipMaps = false;
  64951. }
  64952. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64953. if (!_this.video.autoplay) {
  64954. var oldHandler_1 = _this.video.onplaying;
  64955. var error_1 = false;
  64956. _this.video.onplaying = function () {
  64957. _this.video.onplaying = oldHandler_1;
  64958. _this._texture.isReady = true;
  64959. _this._updateInternalTexture();
  64960. if (!error_1) {
  64961. _this.video.pause();
  64962. }
  64963. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64964. _this.onLoadObservable.notifyObservers(_this);
  64965. }
  64966. };
  64967. var playing = _this.video.play();
  64968. if (playing) {
  64969. playing.then(function () {
  64970. // Everything is good.
  64971. })
  64972. .catch(function () {
  64973. error_1 = true;
  64974. // On Chrome for instance, new policies might prevent playing without user interaction.
  64975. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  64976. _this._onUserActionRequestedObservable.notifyObservers(_this);
  64977. }
  64978. });
  64979. }
  64980. else {
  64981. _this.video.onplaying = oldHandler_1;
  64982. _this._texture.isReady = true;
  64983. _this._updateInternalTexture();
  64984. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64985. _this.onLoadObservable.notifyObservers(_this);
  64986. }
  64987. }
  64988. }
  64989. else {
  64990. _this._texture.isReady = true;
  64991. _this._updateInternalTexture();
  64992. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64993. _this.onLoadObservable.notifyObservers(_this);
  64994. }
  64995. }
  64996. };
  64997. _this.reset = function () {
  64998. if (_this._texture == null) {
  64999. return;
  65000. }
  65001. _this._texture.dispose();
  65002. _this._texture = null;
  65003. };
  65004. _this._updateInternalTexture = function (e) {
  65005. if (_this._texture == null || !_this._texture.isReady) {
  65006. return;
  65007. }
  65008. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  65009. return;
  65010. }
  65011. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  65012. };
  65013. _this._engine = _this.getScene().getEngine();
  65014. _this._generateMipMaps = generateMipMaps;
  65015. _this._samplingMode = samplingMode;
  65016. _this.autoUpdateTexture = settings.autoUpdateTexture;
  65017. _this.name = name || _this._getName(src);
  65018. _this.video = _this._getVideo(src);
  65019. if (settings.poster) {
  65020. _this.video.poster = settings.poster;
  65021. }
  65022. if (settings.autoPlay !== undefined) {
  65023. _this.video.autoplay = settings.autoPlay;
  65024. }
  65025. if (settings.loop !== undefined) {
  65026. _this.video.loop = settings.loop;
  65027. }
  65028. _this.video.setAttribute("playsinline", "");
  65029. _this.video.addEventListener("canplay", _this._createInternalTexture);
  65030. _this.video.addEventListener("paused", _this._updateInternalTexture);
  65031. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  65032. _this.video.addEventListener("emptied", _this.reset);
  65033. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  65034. _this._createInternalTexture();
  65035. }
  65036. return _this;
  65037. }
  65038. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  65039. get: function () {
  65040. if (!this._onUserActionRequestedObservable) {
  65041. this._onUserActionRequestedObservable = new BABYLON.Observable();
  65042. }
  65043. return this._onUserActionRequestedObservable;
  65044. },
  65045. enumerable: true,
  65046. configurable: true
  65047. });
  65048. VideoTexture.prototype._getName = function (src) {
  65049. if (src instanceof HTMLVideoElement) {
  65050. return src.currentSrc;
  65051. }
  65052. if (typeof src === "object") {
  65053. return src.toString();
  65054. }
  65055. return src;
  65056. };
  65057. ;
  65058. VideoTexture.prototype._getVideo = function (src) {
  65059. if (src instanceof HTMLVideoElement) {
  65060. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  65061. return src;
  65062. }
  65063. var video = document.createElement("video");
  65064. if (typeof src === "string") {
  65065. BABYLON.Tools.SetCorsBehavior(src, video);
  65066. video.src = src;
  65067. }
  65068. else {
  65069. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65070. src.forEach(function (url) {
  65071. var source = document.createElement("source");
  65072. source.src = url;
  65073. video.appendChild(source);
  65074. });
  65075. }
  65076. return video;
  65077. };
  65078. ;
  65079. /**
  65080. * Internal method to initiate `update`.
  65081. */
  65082. VideoTexture.prototype._rebuild = function () {
  65083. this.update();
  65084. };
  65085. /**
  65086. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65087. */
  65088. VideoTexture.prototype.update = function () {
  65089. if (!this.autoUpdateTexture) {
  65090. // Expecting user to call `updateTexture` manually
  65091. return;
  65092. }
  65093. this.updateTexture(true);
  65094. };
  65095. /**
  65096. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65097. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65098. */
  65099. VideoTexture.prototype.updateTexture = function (isVisible) {
  65100. if (!isVisible) {
  65101. return;
  65102. }
  65103. if (this.video.paused && this._stillImageCaptured) {
  65104. return;
  65105. }
  65106. this._stillImageCaptured = true;
  65107. this._updateInternalTexture();
  65108. };
  65109. /**
  65110. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65111. * @param url New url.
  65112. */
  65113. VideoTexture.prototype.updateURL = function (url) {
  65114. this.video.src = url;
  65115. };
  65116. VideoTexture.prototype.dispose = function () {
  65117. _super.prototype.dispose.call(this);
  65118. if (this._onUserActionRequestedObservable) {
  65119. this._onUserActionRequestedObservable.clear();
  65120. this._onUserActionRequestedObservable = null;
  65121. }
  65122. this.video.removeEventListener("canplay", this._createInternalTexture);
  65123. this.video.removeEventListener("paused", this._updateInternalTexture);
  65124. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65125. this.video.removeEventListener("emptied", this.reset);
  65126. this.video.pause();
  65127. };
  65128. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65129. var video = document.createElement("video");
  65130. video.setAttribute('autoplay', '');
  65131. video.setAttribute('muted', '');
  65132. video.setAttribute('playsinline', '');
  65133. var constraintsDeviceId;
  65134. if (constraints && constraints.deviceId) {
  65135. constraintsDeviceId = {
  65136. exact: constraints.deviceId,
  65137. };
  65138. }
  65139. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65140. if (navigator.mediaDevices) {
  65141. navigator.mediaDevices.getUserMedia({ video: constraints })
  65142. .then(function (stream) {
  65143. if (video.mozSrcObject !== undefined) {
  65144. // hack for Firefox < 19
  65145. video.mozSrcObject = stream;
  65146. }
  65147. else {
  65148. video.srcObject = stream;
  65149. }
  65150. var onPlaying = function () {
  65151. if (onReady) {
  65152. onReady(new VideoTexture("video", video, scene, true, true));
  65153. }
  65154. video.removeEventListener("playing", onPlaying);
  65155. };
  65156. video.addEventListener("playing", onPlaying);
  65157. video.play();
  65158. })
  65159. .catch(function (err) {
  65160. BABYLON.Tools.Error(err.name);
  65161. });
  65162. }
  65163. else {
  65164. navigator.getUserMedia =
  65165. navigator.getUserMedia ||
  65166. navigator.webkitGetUserMedia ||
  65167. navigator.mozGetUserMedia ||
  65168. navigator.msGetUserMedia;
  65169. if (navigator.getUserMedia) {
  65170. navigator.getUserMedia({
  65171. video: {
  65172. deviceId: constraintsDeviceId,
  65173. width: {
  65174. min: (constraints && constraints.minWidth) || 256,
  65175. max: (constraints && constraints.maxWidth) || 640,
  65176. },
  65177. height: {
  65178. min: (constraints && constraints.minHeight) || 256,
  65179. max: (constraints && constraints.maxHeight) || 480,
  65180. },
  65181. },
  65182. }, function (stream) {
  65183. if (video.mozSrcObject !== undefined) {
  65184. // hack for Firefox < 19
  65185. video.mozSrcObject = stream;
  65186. }
  65187. else {
  65188. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65189. }
  65190. video.play();
  65191. if (onReady) {
  65192. onReady(new VideoTexture("video", video, scene, true, true));
  65193. }
  65194. }, function (e) {
  65195. BABYLON.Tools.Error(e.name);
  65196. });
  65197. }
  65198. }
  65199. };
  65200. return VideoTexture;
  65201. }(BABYLON.Texture));
  65202. BABYLON.VideoTexture = VideoTexture;
  65203. })(BABYLON || (BABYLON = {}));
  65204. //# sourceMappingURL=babylon.videoTexture.js.map
  65205. var BABYLON;
  65206. (function (BABYLON) {
  65207. var RawTexture = /** @class */ (function (_super) {
  65208. __extends(RawTexture, _super);
  65209. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65210. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65211. if (invertY === void 0) { invertY = false; }
  65212. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65213. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65214. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65215. _this.format = format;
  65216. _this._engine = scene.getEngine();
  65217. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65218. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65219. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65220. return _this;
  65221. }
  65222. RawTexture.prototype.update = function (data) {
  65223. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65224. };
  65225. // Statics
  65226. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65227. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65228. if (invertY === void 0) { invertY = false; }
  65229. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65230. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65231. };
  65232. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65233. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65234. if (invertY === void 0) { invertY = false; }
  65235. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65236. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65237. };
  65238. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65239. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65240. if (invertY === void 0) { invertY = false; }
  65241. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65242. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65243. };
  65244. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65245. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65246. if (invertY === void 0) { invertY = false; }
  65247. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65248. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65249. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65250. };
  65251. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65252. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65253. if (invertY === void 0) { invertY = false; }
  65254. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65255. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65256. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65257. };
  65258. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65259. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65260. if (invertY === void 0) { invertY = false; }
  65261. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65262. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65263. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  65264. };
  65265. return RawTexture;
  65266. }(BABYLON.Texture));
  65267. BABYLON.RawTexture = RawTexture;
  65268. })(BABYLON || (BABYLON = {}));
  65269. //# sourceMappingURL=babylon.rawTexture.js.map
  65270. var BABYLON;
  65271. (function (BABYLON) {
  65272. /**
  65273. * Class used to store 3D textures containing user data
  65274. */
  65275. var RawTexture3D = /** @class */ (function (_super) {
  65276. __extends(RawTexture3D, _super);
  65277. /**
  65278. * Create a new RawTexture3D
  65279. * @param data defines the data of the texture
  65280. * @param width defines the width of the texture
  65281. * @param height defines the height of the texture
  65282. * @param depth defines the depth of the texture
  65283. * @param format defines the texture format to use
  65284. * @param scene defines the hosting scene
  65285. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65286. * @param invertY defines if texture must be stored with Y axis inverted
  65287. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65288. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65289. */
  65290. function RawTexture3D(data, width, height, depth,
  65291. /** Gets or sets the texture format to use */
  65292. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65293. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65294. if (invertY === void 0) { invertY = false; }
  65295. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65296. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65297. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65298. _this.format = format;
  65299. _this._engine = scene.getEngine();
  65300. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65301. _this.is3D = true;
  65302. return _this;
  65303. }
  65304. /**
  65305. * Update the texture with new data
  65306. * @param data defines the data to store in the texture
  65307. */
  65308. RawTexture3D.prototype.update = function (data) {
  65309. if (!this._texture) {
  65310. return;
  65311. }
  65312. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65313. };
  65314. return RawTexture3D;
  65315. }(BABYLON.Texture));
  65316. BABYLON.RawTexture3D = RawTexture3D;
  65317. })(BABYLON || (BABYLON = {}));
  65318. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65319. var BABYLON;
  65320. (function (BABYLON) {
  65321. /**
  65322. * PostProcessManager is used to manage one or more post processes or post process pipelines
  65323. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65324. */
  65325. var PostProcessManager = /** @class */ (function () {
  65326. /**
  65327. * Creates a new instance PostProcess
  65328. * @param scene The scene that the post process is associated with.
  65329. */
  65330. function PostProcessManager(scene) {
  65331. this._vertexBuffers = {};
  65332. this._scene = scene;
  65333. }
  65334. PostProcessManager.prototype._prepareBuffers = function () {
  65335. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  65336. return;
  65337. }
  65338. // VBO
  65339. var vertices = [];
  65340. vertices.push(1, 1);
  65341. vertices.push(-1, 1);
  65342. vertices.push(-1, -1);
  65343. vertices.push(1, -1);
  65344. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65345. this._buildIndexBuffer();
  65346. };
  65347. PostProcessManager.prototype._buildIndexBuffer = function () {
  65348. // Indices
  65349. var indices = [];
  65350. indices.push(0);
  65351. indices.push(1);
  65352. indices.push(2);
  65353. indices.push(0);
  65354. indices.push(2);
  65355. indices.push(3);
  65356. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  65357. };
  65358. /**
  65359. * Rebuilds the vertex buffers of the manager.
  65360. */
  65361. PostProcessManager.prototype._rebuild = function () {
  65362. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65363. if (!vb) {
  65364. return;
  65365. }
  65366. vb._rebuild();
  65367. this._buildIndexBuffer();
  65368. };
  65369. // Methods
  65370. /**
  65371. * Prepares a frame to be run through a post process.
  65372. * @param sourceTexture The input texture to the post procesess. (default: null)
  65373. * @param postProcesses An array of post processes to be run. (default: null)
  65374. * @returns True if the post processes were able to be run.
  65375. */
  65376. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  65377. if (sourceTexture === void 0) { sourceTexture = null; }
  65378. if (postProcesses === void 0) { postProcesses = null; }
  65379. var camera = this._scene.activeCamera;
  65380. if (!camera) {
  65381. return false;
  65382. }
  65383. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65384. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65385. return false;
  65386. }
  65387. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  65388. return true;
  65389. };
  65390. /**
  65391. * Manually render a set of post processes to a texture.
  65392. * @param postProcesses An array of post processes to be run.
  65393. * @param targetTexture The target texture to render to.
  65394. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  65395. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  65396. * @param lodLevel defines which lod of the texture to render to
  65397. */
  65398. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  65399. if (targetTexture === void 0) { targetTexture = null; }
  65400. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65401. if (faceIndex === void 0) { faceIndex = 0; }
  65402. if (lodLevel === void 0) { lodLevel = 0; }
  65403. var engine = this._scene.getEngine();
  65404. for (var index = 0; index < postProcesses.length; index++) {
  65405. if (index < postProcesses.length - 1) {
  65406. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  65407. }
  65408. else {
  65409. if (targetTexture) {
  65410. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  65411. }
  65412. else {
  65413. engine.restoreDefaultFramebuffer();
  65414. }
  65415. }
  65416. var pp = postProcesses[index];
  65417. var effect = pp.apply();
  65418. if (effect) {
  65419. pp.onBeforeRenderObservable.notifyObservers(effect);
  65420. // VBOs
  65421. this._prepareBuffers();
  65422. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65423. // Draw order
  65424. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65425. pp.onAfterRenderObservable.notifyObservers(effect);
  65426. }
  65427. }
  65428. // Restore depth buffer
  65429. engine.setDepthBuffer(true);
  65430. engine.setDepthWrite(true);
  65431. };
  65432. /**
  65433. * Finalize the result of the output of the postprocesses.
  65434. * @param doNotPresent If true the result will not be displayed to the screen.
  65435. * @param targetTexture The target texture to render to.
  65436. * @param faceIndex The index of the face to bind the target texture to.
  65437. * @param postProcesses The array of post processes to render.
  65438. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  65439. */
  65440. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  65441. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65442. var camera = this._scene.activeCamera;
  65443. if (!camera) {
  65444. return;
  65445. }
  65446. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65447. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65448. return;
  65449. }
  65450. var engine = this._scene.getEngine();
  65451. for (var index = 0, len = postProcesses.length; index < len; index++) {
  65452. var pp = postProcesses[index];
  65453. if (index < len - 1) {
  65454. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  65455. }
  65456. else {
  65457. if (targetTexture) {
  65458. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  65459. pp._outputTexture = targetTexture;
  65460. }
  65461. else {
  65462. engine.restoreDefaultFramebuffer();
  65463. pp._outputTexture = null;
  65464. }
  65465. }
  65466. if (doNotPresent) {
  65467. break;
  65468. }
  65469. var effect = pp.apply();
  65470. if (effect) {
  65471. pp.onBeforeRenderObservable.notifyObservers(effect);
  65472. // VBOs
  65473. this._prepareBuffers();
  65474. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65475. // Draw order
  65476. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65477. pp.onAfterRenderObservable.notifyObservers(effect);
  65478. }
  65479. }
  65480. // Restore states
  65481. engine.setDepthBuffer(true);
  65482. engine.setDepthWrite(true);
  65483. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65484. };
  65485. /**
  65486. * Disposes of the post process manager.
  65487. */
  65488. PostProcessManager.prototype.dispose = function () {
  65489. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65490. if (buffer) {
  65491. buffer.dispose();
  65492. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65493. }
  65494. if (this._indexBuffer) {
  65495. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65496. this._indexBuffer = null;
  65497. }
  65498. };
  65499. return PostProcessManager;
  65500. }());
  65501. BABYLON.PostProcessManager = PostProcessManager;
  65502. })(BABYLON || (BABYLON = {}));
  65503. //# sourceMappingURL=babylon.postProcessManager.js.map
  65504. var BABYLON;
  65505. (function (BABYLON) {
  65506. /**
  65507. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65508. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65509. */
  65510. var PostProcess = /** @class */ (function () {
  65511. /**
  65512. * Creates a new instance PostProcess
  65513. * @param name The name of the PostProcess.
  65514. * @param fragmentUrl The url of the fragment shader to be used.
  65515. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65516. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65517. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65518. * @param camera The camera to apply the render pass to.
  65519. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65520. * @param engine The engine which the post process will be applied. (default: current engine)
  65521. * @param reusable If the post process can be reused on the same frame. (default: false)
  65522. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65523. * @param textureType Type of textures used when performing the post process. (default: 0)
  65524. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65525. * @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
  65526. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65527. */
  65528. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65529. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65530. if (defines === void 0) { defines = null; }
  65531. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65532. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65533. if (blockCompilation === void 0) { blockCompilation = false; }
  65534. this.name = name;
  65535. /**
  65536. * Width of the texture to apply the post process on
  65537. */
  65538. this.width = -1;
  65539. /**
  65540. * Height of the texture to apply the post process on
  65541. */
  65542. this.height = -1;
  65543. /**
  65544. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65545. */
  65546. this._outputTexture = null;
  65547. /**
  65548. * If the buffer needs to be cleared before applying the post process. (default: true)
  65549. * Should be set to false if shader will overwrite all previous pixels.
  65550. */
  65551. this.autoClear = true;
  65552. /**
  65553. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65554. */
  65555. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65556. /**
  65557. * Animations to be used for the post processing
  65558. */
  65559. this.animations = new Array();
  65560. /**
  65561. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65562. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65563. */
  65564. this.enablePixelPerfectMode = false;
  65565. /**
  65566. * Force the postprocess to be applied without taking in account viewport
  65567. */
  65568. this.forceFullscreenViewport = true;
  65569. /**
  65570. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65571. *
  65572. * | Value | Type | Description |
  65573. * | ----- | ----------------------------------- | ----------- |
  65574. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65575. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65576. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65577. *
  65578. */
  65579. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65580. /**
  65581. * Force textures to be a power of two (default: false)
  65582. */
  65583. this.alwaysForcePOT = false;
  65584. /**
  65585. * Number of sample textures (default: 1)
  65586. */
  65587. this.samples = 1;
  65588. /**
  65589. * Modify the scale of the post process to be the same as the viewport (default: false)
  65590. */
  65591. this.adaptScaleToCurrentViewport = false;
  65592. this._reusable = false;
  65593. /**
  65594. * Smart array of input and output textures for the post process.
  65595. */
  65596. this._textures = new BABYLON.SmartArray(2);
  65597. /**
  65598. * The index in _textures that corresponds to the output texture.
  65599. */
  65600. this._currentRenderTextureInd = 0;
  65601. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65602. this._texelSize = BABYLON.Vector2.Zero();
  65603. // Events
  65604. /**
  65605. * An event triggered when the postprocess is activated.
  65606. */
  65607. this.onActivateObservable = new BABYLON.Observable();
  65608. /**
  65609. * An event triggered when the postprocess changes its size.
  65610. */
  65611. this.onSizeChangedObservable = new BABYLON.Observable();
  65612. /**
  65613. * An event triggered when the postprocess applies its effect.
  65614. */
  65615. this.onApplyObservable = new BABYLON.Observable();
  65616. /**
  65617. * An event triggered before rendering the postprocess
  65618. */
  65619. this.onBeforeRenderObservable = new BABYLON.Observable();
  65620. /**
  65621. * An event triggered after rendering the postprocess
  65622. */
  65623. this.onAfterRenderObservable = new BABYLON.Observable();
  65624. if (camera != null) {
  65625. this._camera = camera;
  65626. this._scene = camera.getScene();
  65627. camera.attachPostProcess(this);
  65628. this._engine = this._scene.getEngine();
  65629. this._scene.postProcesses.push(this);
  65630. }
  65631. else if (engine) {
  65632. this._engine = engine;
  65633. this._engine.postProcesses.push(this);
  65634. }
  65635. this._options = options;
  65636. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65637. this._reusable = reusable || false;
  65638. this._textureType = textureType;
  65639. this._samplers = samplers || [];
  65640. this._samplers.push("textureSampler");
  65641. this._fragmentUrl = fragmentUrl;
  65642. this._vertexUrl = vertexUrl;
  65643. this._parameters = parameters || [];
  65644. this._parameters.push("scale");
  65645. this._indexParameters = indexParameters;
  65646. if (!blockCompilation) {
  65647. this.updateEffect(defines);
  65648. }
  65649. }
  65650. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65651. /**
  65652. * A function that is added to the onActivateObservable
  65653. */
  65654. set: function (callback) {
  65655. if (this._onActivateObserver) {
  65656. this.onActivateObservable.remove(this._onActivateObserver);
  65657. }
  65658. if (callback) {
  65659. this._onActivateObserver = this.onActivateObservable.add(callback);
  65660. }
  65661. },
  65662. enumerable: true,
  65663. configurable: true
  65664. });
  65665. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65666. /**
  65667. * A function that is added to the onSizeChangedObservable
  65668. */
  65669. set: function (callback) {
  65670. if (this._onSizeChangedObserver) {
  65671. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65672. }
  65673. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65674. },
  65675. enumerable: true,
  65676. configurable: true
  65677. });
  65678. Object.defineProperty(PostProcess.prototype, "onApply", {
  65679. /**
  65680. * A function that is added to the onApplyObservable
  65681. */
  65682. set: function (callback) {
  65683. if (this._onApplyObserver) {
  65684. this.onApplyObservable.remove(this._onApplyObserver);
  65685. }
  65686. this._onApplyObserver = this.onApplyObservable.add(callback);
  65687. },
  65688. enumerable: true,
  65689. configurable: true
  65690. });
  65691. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65692. /**
  65693. * A function that is added to the onBeforeRenderObservable
  65694. */
  65695. set: function (callback) {
  65696. if (this._onBeforeRenderObserver) {
  65697. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65698. }
  65699. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65700. },
  65701. enumerable: true,
  65702. configurable: true
  65703. });
  65704. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65705. /**
  65706. * A function that is added to the onAfterRenderObservable
  65707. */
  65708. set: function (callback) {
  65709. if (this._onAfterRenderObserver) {
  65710. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65711. }
  65712. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65713. },
  65714. enumerable: true,
  65715. configurable: true
  65716. });
  65717. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65718. /**
  65719. * 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
  65720. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65721. */
  65722. get: function () {
  65723. return this._textures.data[this._currentRenderTextureInd];
  65724. },
  65725. set: function (value) {
  65726. this._forcedOutputTexture = value;
  65727. },
  65728. enumerable: true,
  65729. configurable: true
  65730. });
  65731. /**
  65732. * Gets the camera which post process is applied to.
  65733. * @returns The camera the post process is applied to.
  65734. */
  65735. PostProcess.prototype.getCamera = function () {
  65736. return this._camera;
  65737. };
  65738. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65739. /**
  65740. * Gets the texel size of the postprocess.
  65741. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65742. */
  65743. get: function () {
  65744. if (this._shareOutputWithPostProcess) {
  65745. return this._shareOutputWithPostProcess.texelSize;
  65746. }
  65747. if (this._forcedOutputTexture) {
  65748. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65749. }
  65750. return this._texelSize;
  65751. },
  65752. enumerable: true,
  65753. configurable: true
  65754. });
  65755. /**
  65756. * Gets the engine which this post process belongs to.
  65757. * @returns The engine the post process was enabled with.
  65758. */
  65759. PostProcess.prototype.getEngine = function () {
  65760. return this._engine;
  65761. };
  65762. /**
  65763. * The effect that is created when initializing the post process.
  65764. * @returns The created effect corrisponding the the postprocess.
  65765. */
  65766. PostProcess.prototype.getEffect = function () {
  65767. return this._effect;
  65768. };
  65769. /**
  65770. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65771. * @param postProcess The post process to share the output with.
  65772. * @returns This post process.
  65773. */
  65774. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65775. this._disposeTextures();
  65776. this._shareOutputWithPostProcess = postProcess;
  65777. return this;
  65778. };
  65779. /**
  65780. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65781. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65782. */
  65783. PostProcess.prototype.useOwnOutput = function () {
  65784. if (this._textures.length == 0) {
  65785. this._textures = new BABYLON.SmartArray(2);
  65786. }
  65787. this._shareOutputWithPostProcess = null;
  65788. };
  65789. /**
  65790. * Updates the effect with the current post process compile time values and recompiles the shader.
  65791. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65792. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65793. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65794. * @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
  65795. * @param onCompiled Called when the shader has been compiled.
  65796. * @param onError Called if there is an error when compiling a shader.
  65797. */
  65798. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65799. if (defines === void 0) { defines = null; }
  65800. if (uniforms === void 0) { uniforms = null; }
  65801. if (samplers === void 0) { samplers = null; }
  65802. 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);
  65803. };
  65804. /**
  65805. * The post process is reusable if it can be used multiple times within one frame.
  65806. * @returns If the post process is reusable
  65807. */
  65808. PostProcess.prototype.isReusable = function () {
  65809. return this._reusable;
  65810. };
  65811. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65812. PostProcess.prototype.markTextureDirty = function () {
  65813. this.width = -1;
  65814. };
  65815. /**
  65816. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65817. * 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.
  65818. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65819. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65820. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65821. * @returns The target texture that was bound to be written to.
  65822. */
  65823. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65824. var _this = this;
  65825. if (sourceTexture === void 0) { sourceTexture = null; }
  65826. camera = camera || this._camera;
  65827. var scene = camera.getScene();
  65828. var engine = scene.getEngine();
  65829. var maxSize = engine.getCaps().maxTextureSize;
  65830. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65831. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65832. // 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
  65833. var webVRCamera = camera.parent;
  65834. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65835. requiredWidth /= 2;
  65836. }
  65837. var desiredWidth = (this._options.width || requiredWidth);
  65838. var desiredHeight = this._options.height || requiredHeight;
  65839. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65840. if (this.adaptScaleToCurrentViewport) {
  65841. var currentViewport = engine.currentViewport;
  65842. if (currentViewport) {
  65843. desiredWidth *= currentViewport.width;
  65844. desiredHeight *= currentViewport.height;
  65845. }
  65846. }
  65847. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65848. if (!this._options.width) {
  65849. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65850. }
  65851. if (!this._options.height) {
  65852. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65853. }
  65854. }
  65855. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65856. if (this._textures.length > 0) {
  65857. for (var i = 0; i < this._textures.length; i++) {
  65858. this._engine._releaseTexture(this._textures.data[i]);
  65859. }
  65860. this._textures.reset();
  65861. }
  65862. this.width = desiredWidth;
  65863. this.height = desiredHeight;
  65864. var textureSize = { width: this.width, height: this.height };
  65865. var textureOptions = {
  65866. generateMipMaps: false,
  65867. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65868. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65869. samplingMode: this.renderTargetSamplingMode,
  65870. type: this._textureType
  65871. };
  65872. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65873. if (this._reusable) {
  65874. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65875. }
  65876. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65877. this.onSizeChangedObservable.notifyObservers(this);
  65878. }
  65879. this._textures.forEach(function (texture) {
  65880. if (texture.samples !== _this.samples) {
  65881. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65882. }
  65883. });
  65884. }
  65885. var target;
  65886. if (this._shareOutputWithPostProcess) {
  65887. target = this._shareOutputWithPostProcess.inputTexture;
  65888. }
  65889. else if (this._forcedOutputTexture) {
  65890. target = this._forcedOutputTexture;
  65891. this.width = this._forcedOutputTexture.width;
  65892. this.height = this._forcedOutputTexture.height;
  65893. }
  65894. else {
  65895. target = this.inputTexture;
  65896. }
  65897. // Bind the input of this post process to be used as the output of the previous post process.
  65898. if (this.enablePixelPerfectMode) {
  65899. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65900. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65901. }
  65902. else {
  65903. this._scaleRatio.copyFromFloats(1, 1);
  65904. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65905. }
  65906. this.onActivateObservable.notifyObservers(camera);
  65907. // Clear
  65908. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65909. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65910. }
  65911. if (this._reusable) {
  65912. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65913. }
  65914. return target;
  65915. };
  65916. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65917. /**
  65918. * If the post process is supported.
  65919. */
  65920. get: function () {
  65921. return this._effect.isSupported;
  65922. },
  65923. enumerable: true,
  65924. configurable: true
  65925. });
  65926. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65927. /**
  65928. * The aspect ratio of the output texture.
  65929. */
  65930. get: function () {
  65931. if (this._shareOutputWithPostProcess) {
  65932. return this._shareOutputWithPostProcess.aspectRatio;
  65933. }
  65934. if (this._forcedOutputTexture) {
  65935. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65936. }
  65937. return this.width / this.height;
  65938. },
  65939. enumerable: true,
  65940. configurable: true
  65941. });
  65942. /**
  65943. * Get a value indicating if the post-process is ready to be used
  65944. * @returns true if the post-process is ready (shader is compiled)
  65945. */
  65946. PostProcess.prototype.isReady = function () {
  65947. return this._effect && this._effect.isReady();
  65948. };
  65949. /**
  65950. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65951. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65952. */
  65953. PostProcess.prototype.apply = function () {
  65954. // Check
  65955. if (!this._effect || !this._effect.isReady())
  65956. return null;
  65957. // States
  65958. this._engine.enableEffect(this._effect);
  65959. this._engine.setState(false);
  65960. this._engine.setDepthBuffer(false);
  65961. this._engine.setDepthWrite(false);
  65962. // Alpha
  65963. this._engine.setAlphaMode(this.alphaMode);
  65964. if (this.alphaConstants) {
  65965. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65966. }
  65967. // Bind the output texture of the preivous post process as the input to this post process.
  65968. var source;
  65969. if (this._shareOutputWithPostProcess) {
  65970. source = this._shareOutputWithPostProcess.inputTexture;
  65971. }
  65972. else if (this._forcedOutputTexture) {
  65973. source = this._forcedOutputTexture;
  65974. }
  65975. else {
  65976. source = this.inputTexture;
  65977. }
  65978. this._effect._bindTexture("textureSampler", source);
  65979. // Parameters
  65980. this._effect.setVector2("scale", this._scaleRatio);
  65981. this.onApplyObservable.notifyObservers(this._effect);
  65982. return this._effect;
  65983. };
  65984. PostProcess.prototype._disposeTextures = function () {
  65985. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65986. return;
  65987. }
  65988. if (this._textures.length > 0) {
  65989. for (var i = 0; i < this._textures.length; i++) {
  65990. this._engine._releaseTexture(this._textures.data[i]);
  65991. }
  65992. }
  65993. this._textures.dispose();
  65994. };
  65995. /**
  65996. * Disposes the post process.
  65997. * @param camera The camera to dispose the post process on.
  65998. */
  65999. PostProcess.prototype.dispose = function (camera) {
  66000. camera = camera || this._camera;
  66001. this._disposeTextures();
  66002. if (this._scene) {
  66003. var index_1 = this._scene.postProcesses.indexOf(this);
  66004. if (index_1 !== -1) {
  66005. this._scene.postProcesses.splice(index_1, 1);
  66006. }
  66007. }
  66008. else {
  66009. var index_2 = this._engine.postProcesses.indexOf(this);
  66010. if (index_2 !== -1) {
  66011. this._engine.postProcesses.splice(index_2, 1);
  66012. }
  66013. }
  66014. if (!camera) {
  66015. return;
  66016. }
  66017. camera.detachPostProcess(this);
  66018. var index = camera._postProcesses.indexOf(this);
  66019. if (index === 0 && camera._postProcesses.length > 0) {
  66020. var firstPostProcess = this._camera._getFirstPostProcess();
  66021. if (firstPostProcess) {
  66022. firstPostProcess.markTextureDirty();
  66023. }
  66024. }
  66025. this.onActivateObservable.clear();
  66026. this.onAfterRenderObservable.clear();
  66027. this.onApplyObservable.clear();
  66028. this.onBeforeRenderObservable.clear();
  66029. this.onSizeChangedObservable.clear();
  66030. };
  66031. return PostProcess;
  66032. }());
  66033. BABYLON.PostProcess = PostProcess;
  66034. })(BABYLON || (BABYLON = {}));
  66035. //# sourceMappingURL=babylon.postProcess.js.map
  66036. var BABYLON;
  66037. (function (BABYLON) {
  66038. var PassPostProcess = /** @class */ (function (_super) {
  66039. __extends(PassPostProcess, _super);
  66040. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  66041. if (camera === void 0) { camera = null; }
  66042. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66043. if (blockCompilation === void 0) { blockCompilation = false; }
  66044. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  66045. }
  66046. return PassPostProcess;
  66047. }(BABYLON.PostProcess));
  66048. BABYLON.PassPostProcess = PassPostProcess;
  66049. })(BABYLON || (BABYLON = {}));
  66050. //# sourceMappingURL=babylon.passPostProcess.js.map
  66051. var __assign = (this && this.__assign) || Object.assign || function(t) {
  66052. for (var s, i = 1, n = arguments.length; i < n; i++) {
  66053. s = arguments[i];
  66054. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  66055. t[p] = s[p];
  66056. }
  66057. return t;
  66058. };
  66059. var BABYLON;
  66060. (function (BABYLON) {
  66061. /**
  66062. * Default implementation IShadowGenerator.
  66063. * This is the main object responsible of generating shadows in the framework.
  66064. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  66065. */
  66066. var ShadowGenerator = /** @class */ (function () {
  66067. /**
  66068. * Creates a ShadowGenerator object.
  66069. * A ShadowGenerator is the required tool to use the shadows.
  66070. * Each light casting shadows needs to use its own ShadowGenerator.
  66071. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  66072. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  66073. * @param light The light object generating the shadows.
  66074. * @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.
  66075. */
  66076. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  66077. this._bias = 0.00005;
  66078. this._normalBias = 0;
  66079. this._blurBoxOffset = 1;
  66080. this._blurScale = 2;
  66081. this._blurKernel = 1;
  66082. this._useKernelBlur = false;
  66083. this._filter = ShadowGenerator.FILTER_NONE;
  66084. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  66085. this._contactHardeningLightSizeUVRatio = 0.1;
  66086. this._darkness = 0;
  66087. this._transparencyShadow = false;
  66088. /**
  66089. * Controls the extent to which the shadows fade out at the edge of the frustum
  66090. * Used only by directionals and spots
  66091. */
  66092. this.frustumEdgeFalloff = 0;
  66093. /**
  66094. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  66095. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  66096. * It might on the other hand introduce peter panning.
  66097. */
  66098. this.forceBackFacesOnly = false;
  66099. this._lightDirection = BABYLON.Vector3.Zero();
  66100. this._viewMatrix = BABYLON.Matrix.Zero();
  66101. this._projectionMatrix = BABYLON.Matrix.Zero();
  66102. this._transformMatrix = BABYLON.Matrix.Zero();
  66103. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66104. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66105. this._currentFaceIndex = 0;
  66106. this._currentFaceIndexCache = 0;
  66107. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  66108. this._mapSize = mapSize;
  66109. this._light = light;
  66110. this._scene = light.getScene();
  66111. light._shadowGenerator = this;
  66112. // Texture type fallback from float to int if not supported.
  66113. var caps = this._scene.getEngine().getCaps();
  66114. if (!useFullFloatFirst) {
  66115. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66116. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66117. }
  66118. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66119. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66120. }
  66121. else {
  66122. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66123. }
  66124. }
  66125. else {
  66126. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66127. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66128. }
  66129. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66130. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66131. }
  66132. else {
  66133. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66134. }
  66135. }
  66136. this._initializeGenerator();
  66137. this._applyFilterValues();
  66138. }
  66139. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  66140. /**
  66141. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  66142. */
  66143. get: function () {
  66144. return this._bias;
  66145. },
  66146. /**
  66147. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  66148. */
  66149. set: function (bias) {
  66150. this._bias = bias;
  66151. },
  66152. enumerable: true,
  66153. configurable: true
  66154. });
  66155. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  66156. /**
  66157. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66158. */
  66159. get: function () {
  66160. return this._normalBias;
  66161. },
  66162. /**
  66163. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66164. */
  66165. set: function (normalBias) {
  66166. this._normalBias = normalBias;
  66167. },
  66168. enumerable: true,
  66169. configurable: true
  66170. });
  66171. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  66172. /**
  66173. * Gets the blur box offset: offset applied during the blur pass.
  66174. * Only usefull if useKernelBlur = false
  66175. */
  66176. get: function () {
  66177. return this._blurBoxOffset;
  66178. },
  66179. /**
  66180. * Sets the blur box offset: offset applied during the blur pass.
  66181. * Only usefull if useKernelBlur = false
  66182. */
  66183. set: function (value) {
  66184. if (this._blurBoxOffset === value) {
  66185. return;
  66186. }
  66187. this._blurBoxOffset = value;
  66188. this._disposeBlurPostProcesses();
  66189. },
  66190. enumerable: true,
  66191. configurable: true
  66192. });
  66193. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  66194. /**
  66195. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  66196. * 2 means half of the size.
  66197. */
  66198. get: function () {
  66199. return this._blurScale;
  66200. },
  66201. /**
  66202. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  66203. * 2 means half of the size.
  66204. */
  66205. set: function (value) {
  66206. if (this._blurScale === value) {
  66207. return;
  66208. }
  66209. this._blurScale = value;
  66210. this._disposeBlurPostProcesses();
  66211. },
  66212. enumerable: true,
  66213. configurable: true
  66214. });
  66215. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  66216. /**
  66217. * Gets the blur kernel: kernel size of the blur pass.
  66218. * Only usefull if useKernelBlur = true
  66219. */
  66220. get: function () {
  66221. return this._blurKernel;
  66222. },
  66223. /**
  66224. * Sets the blur kernel: kernel size of the blur pass.
  66225. * Only usefull if useKernelBlur = true
  66226. */
  66227. set: function (value) {
  66228. if (this._blurKernel === value) {
  66229. return;
  66230. }
  66231. this._blurKernel = value;
  66232. this._disposeBlurPostProcesses();
  66233. },
  66234. enumerable: true,
  66235. configurable: true
  66236. });
  66237. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66238. /**
  66239. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66240. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66241. */
  66242. get: function () {
  66243. return this._useKernelBlur;
  66244. },
  66245. /**
  66246. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66247. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66248. */
  66249. set: function (value) {
  66250. if (this._useKernelBlur === value) {
  66251. return;
  66252. }
  66253. this._useKernelBlur = value;
  66254. this._disposeBlurPostProcesses();
  66255. },
  66256. enumerable: true,
  66257. configurable: true
  66258. });
  66259. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66260. /**
  66261. * Gets the depth scale used in ESM mode.
  66262. */
  66263. get: function () {
  66264. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66265. },
  66266. /**
  66267. * Sets the depth scale used in ESM mode.
  66268. * This can override the scale stored on the light.
  66269. */
  66270. set: function (value) {
  66271. this._depthScale = value;
  66272. },
  66273. enumerable: true,
  66274. configurable: true
  66275. });
  66276. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66277. /**
  66278. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66279. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66280. */
  66281. get: function () {
  66282. return this._filter;
  66283. },
  66284. /**
  66285. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66286. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66287. */
  66288. set: function (value) {
  66289. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66290. if (this._light.needCube()) {
  66291. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66292. this.useExponentialShadowMap = true;
  66293. return;
  66294. }
  66295. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66296. this.useCloseExponentialShadowMap = true;
  66297. return;
  66298. }
  66299. // PCF on cubemap would also be expensive
  66300. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66301. this.usePoissonSampling = true;
  66302. return;
  66303. }
  66304. }
  66305. // Weblg1 fallback for PCF.
  66306. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66307. if (this._scene.getEngine().webGLVersion === 1) {
  66308. this.usePoissonSampling = true;
  66309. return;
  66310. }
  66311. }
  66312. if (this._filter === value) {
  66313. return;
  66314. }
  66315. this._filter = value;
  66316. this._disposeBlurPostProcesses();
  66317. this._applyFilterValues();
  66318. this._light._markMeshesAsLightDirty();
  66319. },
  66320. enumerable: true,
  66321. configurable: true
  66322. });
  66323. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66324. /**
  66325. * Gets if the current filter is set to Poisson Sampling.
  66326. */
  66327. get: function () {
  66328. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66329. },
  66330. /**
  66331. * Sets the current filter to Poisson Sampling.
  66332. */
  66333. set: function (value) {
  66334. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66335. return;
  66336. }
  66337. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66338. },
  66339. enumerable: true,
  66340. configurable: true
  66341. });
  66342. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66343. /**
  66344. * Gets if the current filter is set to VSM.
  66345. * DEPRECATED. Should use useExponentialShadowMap instead.
  66346. */
  66347. get: function () {
  66348. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66349. return this.useExponentialShadowMap;
  66350. },
  66351. /**
  66352. * Sets the current filter is to VSM.
  66353. * DEPRECATED. Should use useExponentialShadowMap instead.
  66354. */
  66355. set: function (value) {
  66356. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66357. this.useExponentialShadowMap = value;
  66358. },
  66359. enumerable: true,
  66360. configurable: true
  66361. });
  66362. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66363. /**
  66364. * Gets if the current filter is set to blurred VSM.
  66365. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66366. */
  66367. get: function () {
  66368. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66369. return this.useBlurExponentialShadowMap;
  66370. },
  66371. /**
  66372. * Sets the current filter is to blurred VSM.
  66373. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66374. */
  66375. set: function (value) {
  66376. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66377. this.useBlurExponentialShadowMap = value;
  66378. },
  66379. enumerable: true,
  66380. configurable: true
  66381. });
  66382. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66383. /**
  66384. * Gets if the current filter is set to ESM.
  66385. */
  66386. get: function () {
  66387. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66388. },
  66389. /**
  66390. * Sets the current filter is to ESM.
  66391. */
  66392. set: function (value) {
  66393. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66394. return;
  66395. }
  66396. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66397. },
  66398. enumerable: true,
  66399. configurable: true
  66400. });
  66401. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66402. /**
  66403. * Gets if the current filter is set to filtered ESM.
  66404. */
  66405. get: function () {
  66406. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66407. },
  66408. /**
  66409. * Gets if the current filter is set to filtered ESM.
  66410. */
  66411. set: function (value) {
  66412. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66413. return;
  66414. }
  66415. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66416. },
  66417. enumerable: true,
  66418. configurable: true
  66419. });
  66420. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66421. /**
  66422. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66423. * exponential to prevent steep falloff artifacts).
  66424. */
  66425. get: function () {
  66426. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66427. },
  66428. /**
  66429. * Sets the current filter to "close ESM" (using the inverse of the
  66430. * exponential to prevent steep falloff artifacts).
  66431. */
  66432. set: function (value) {
  66433. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66434. return;
  66435. }
  66436. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66437. },
  66438. enumerable: true,
  66439. configurable: true
  66440. });
  66441. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66442. /**
  66443. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66444. * exponential to prevent steep falloff artifacts).
  66445. */
  66446. get: function () {
  66447. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66448. },
  66449. /**
  66450. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66451. * exponential to prevent steep falloff artifacts).
  66452. */
  66453. set: function (value) {
  66454. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66455. return;
  66456. }
  66457. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66458. },
  66459. enumerable: true,
  66460. configurable: true
  66461. });
  66462. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66463. /**
  66464. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66465. */
  66466. get: function () {
  66467. return this.filter === ShadowGenerator.FILTER_PCF;
  66468. },
  66469. /**
  66470. * Sets the current filter to "PCF" (percentage closer filtering).
  66471. */
  66472. set: function (value) {
  66473. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66474. return;
  66475. }
  66476. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66477. },
  66478. enumerable: true,
  66479. configurable: true
  66480. });
  66481. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66482. /**
  66483. * Gets the PCF or PCSS Quality.
  66484. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66485. */
  66486. get: function () {
  66487. return this._filteringQuality;
  66488. },
  66489. /**
  66490. * Sets the PCF or PCSS Quality.
  66491. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66492. */
  66493. set: function (filteringQuality) {
  66494. this._filteringQuality = filteringQuality;
  66495. },
  66496. enumerable: true,
  66497. configurable: true
  66498. });
  66499. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66500. /**
  66501. * Gets if the current filter is set to "PCSS" (contact hardening).
  66502. */
  66503. get: function () {
  66504. return this.filter === ShadowGenerator.FILTER_PCSS;
  66505. },
  66506. /**
  66507. * Sets the current filter to "PCSS" (contact hardening).
  66508. */
  66509. set: function (value) {
  66510. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66511. return;
  66512. }
  66513. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66514. },
  66515. enumerable: true,
  66516. configurable: true
  66517. });
  66518. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66519. /**
  66520. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66521. * Using a ratio helps keeping shape stability independently of the map size.
  66522. *
  66523. * It does not account for the light projection as it was having too much
  66524. * instability during the light setup or during light position changes.
  66525. *
  66526. * Only valid if useContactHardeningShadow is true.
  66527. */
  66528. get: function () {
  66529. return this._contactHardeningLightSizeUVRatio;
  66530. },
  66531. /**
  66532. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66533. * Using a ratio helps keeping shape stability independently of the map size.
  66534. *
  66535. * It does not account for the light projection as it was having too much
  66536. * instability during the light setup or during light position changes.
  66537. *
  66538. * Only valid if useContactHardeningShadow is true.
  66539. */
  66540. set: function (contactHardeningLightSizeUVRatio) {
  66541. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66542. },
  66543. enumerable: true,
  66544. configurable: true
  66545. });
  66546. /**
  66547. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66548. * 0 means strongest and 1 would means no shadow.
  66549. * @returns the darkness.
  66550. */
  66551. ShadowGenerator.prototype.getDarkness = function () {
  66552. return this._darkness;
  66553. };
  66554. /**
  66555. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66556. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66557. * @returns the shadow generator allowing fluent coding.
  66558. */
  66559. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66560. if (darkness >= 1.0)
  66561. this._darkness = 1.0;
  66562. else if (darkness <= 0.0)
  66563. this._darkness = 0.0;
  66564. else
  66565. this._darkness = darkness;
  66566. return this;
  66567. };
  66568. /**
  66569. * Sets the ability to have transparent shadow (boolean).
  66570. * @param transparent True if transparent else False
  66571. * @returns the shadow generator allowing fluent coding
  66572. */
  66573. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66574. this._transparencyShadow = transparent;
  66575. return this;
  66576. };
  66577. /**
  66578. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66579. * @returns The render target texture if present otherwise, null
  66580. */
  66581. ShadowGenerator.prototype.getShadowMap = function () {
  66582. return this._shadowMap;
  66583. };
  66584. /**
  66585. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66586. * @returns The render target texture if the shadow map is present otherwise, null
  66587. */
  66588. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66589. if (this._shadowMap2) {
  66590. return this._shadowMap2;
  66591. }
  66592. return this._shadowMap;
  66593. };
  66594. /**
  66595. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66596. * @param mesh Mesh to add
  66597. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66598. * @returns the Shadow Generator itself
  66599. */
  66600. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66601. if (includeDescendants === void 0) { includeDescendants = true; }
  66602. if (!this._shadowMap) {
  66603. return this;
  66604. }
  66605. if (!this._shadowMap.renderList) {
  66606. this._shadowMap.renderList = [];
  66607. }
  66608. this._shadowMap.renderList.push(mesh);
  66609. if (includeDescendants) {
  66610. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66611. }
  66612. return this;
  66613. var _a;
  66614. };
  66615. /**
  66616. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66617. * @param mesh Mesh to remove
  66618. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66619. * @returns the Shadow Generator itself
  66620. */
  66621. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66622. if (includeDescendants === void 0) { includeDescendants = true; }
  66623. if (!this._shadowMap || !this._shadowMap.renderList) {
  66624. return this;
  66625. }
  66626. var index = this._shadowMap.renderList.indexOf(mesh);
  66627. if (index !== -1) {
  66628. this._shadowMap.renderList.splice(index, 1);
  66629. }
  66630. if (includeDescendants) {
  66631. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66632. var child = _a[_i];
  66633. this.removeShadowCaster(child);
  66634. }
  66635. }
  66636. return this;
  66637. };
  66638. /**
  66639. * Returns the associated light object.
  66640. * @returns the light generating the shadow
  66641. */
  66642. ShadowGenerator.prototype.getLight = function () {
  66643. return this._light;
  66644. };
  66645. ShadowGenerator.prototype._initializeGenerator = function () {
  66646. this._light._markMeshesAsLightDirty();
  66647. this._initializeShadowMap();
  66648. };
  66649. ShadowGenerator.prototype._initializeShadowMap = function () {
  66650. var _this = this;
  66651. // Render target
  66652. var engine = this._scene.getEngine();
  66653. if (engine.webGLVersion > 1) {
  66654. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66655. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66656. }
  66657. else {
  66658. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66659. }
  66660. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66661. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66662. this._shadowMap.anisotropicFilteringLevel = 1;
  66663. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66664. this._shadowMap.renderParticles = false;
  66665. this._shadowMap.ignoreCameraViewport = true;
  66666. // Record Face Index before render.
  66667. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66668. _this._currentFaceIndex = faceIndex;
  66669. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66670. engine.setColorWrite(false);
  66671. }
  66672. });
  66673. // Custom render function.
  66674. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66675. // Blur if required afer render.
  66676. this._shadowMap.onAfterUnbindObservable.add(function () {
  66677. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66678. engine.setColorWrite(true);
  66679. }
  66680. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66681. return;
  66682. }
  66683. var shadowMap = _this.getShadowMapForRendering();
  66684. if (shadowMap) {
  66685. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66686. }
  66687. });
  66688. // Clear according to the chosen filter.
  66689. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66690. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66691. this._shadowMap.onClearObservable.add(function (engine) {
  66692. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66693. engine.clear(clearOne, false, true, false);
  66694. }
  66695. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66696. engine.clear(clearZero, true, true, false);
  66697. }
  66698. else {
  66699. engine.clear(clearOne, true, true, false);
  66700. }
  66701. });
  66702. };
  66703. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66704. var _this = this;
  66705. var engine = this._scene.getEngine();
  66706. var targetSize = this._mapSize / this.blurScale;
  66707. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66708. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66709. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66710. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66711. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66712. }
  66713. if (this.useKernelBlur) {
  66714. 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);
  66715. this._kernelBlurXPostprocess.width = targetSize;
  66716. this._kernelBlurXPostprocess.height = targetSize;
  66717. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66718. effect.setTexture("textureSampler", _this._shadowMap);
  66719. });
  66720. 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);
  66721. this._kernelBlurXPostprocess.autoClear = false;
  66722. this._kernelBlurYPostprocess.autoClear = false;
  66723. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66724. this._kernelBlurXPostprocess.packedFloat = true;
  66725. this._kernelBlurYPostprocess.packedFloat = true;
  66726. }
  66727. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66728. }
  66729. else {
  66730. 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);
  66731. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66732. effect.setFloat2("screenSize", targetSize, targetSize);
  66733. effect.setTexture("textureSampler", _this._shadowMap);
  66734. });
  66735. this._boxBlurPostprocess.autoClear = false;
  66736. this._blurPostProcesses = [this._boxBlurPostprocess];
  66737. }
  66738. };
  66739. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66740. var index;
  66741. var engine = this._scene.getEngine();
  66742. if (depthOnlySubMeshes.length) {
  66743. engine.setColorWrite(false);
  66744. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66745. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66746. }
  66747. engine.setColorWrite(true);
  66748. }
  66749. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66750. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66751. }
  66752. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66753. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66754. }
  66755. if (this._transparencyShadow) {
  66756. for (index = 0; index < transparentSubMeshes.length; index++) {
  66757. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66758. }
  66759. }
  66760. };
  66761. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66762. var _this = this;
  66763. var mesh = subMesh.getRenderingMesh();
  66764. var scene = this._scene;
  66765. var engine = scene.getEngine();
  66766. var material = subMesh.getMaterial();
  66767. if (!material) {
  66768. return;
  66769. }
  66770. // Culling
  66771. engine.setState(material.backFaceCulling);
  66772. // Managing instances
  66773. var batch = mesh._getInstancesRenderList(subMesh._id);
  66774. if (batch.mustReturn) {
  66775. return;
  66776. }
  66777. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66778. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66779. engine.enableEffect(this._effect);
  66780. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66781. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66782. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66783. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66784. this._effect.setVector3("lightData", this._cachedDirection);
  66785. }
  66786. else {
  66787. this._effect.setVector3("lightData", this._cachedPosition);
  66788. }
  66789. if (scene.activeCamera) {
  66790. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66791. }
  66792. // Alpha test
  66793. if (material && material.needAlphaTesting()) {
  66794. var alphaTexture = material.getAlphaTestTexture();
  66795. if (alphaTexture) {
  66796. this._effect.setTexture("diffuseSampler", alphaTexture);
  66797. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66798. }
  66799. }
  66800. // Bones
  66801. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66802. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66803. }
  66804. // Morph targets
  66805. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66806. if (this.forceBackFacesOnly) {
  66807. engine.setState(true, 0, false, true);
  66808. }
  66809. // Draw
  66810. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66811. if (this.forceBackFacesOnly) {
  66812. engine.setState(true, 0, false, false);
  66813. }
  66814. }
  66815. else {
  66816. // Need to reset refresh rate of the shadowMap
  66817. if (this._shadowMap) {
  66818. this._shadowMap.resetRefreshCounter();
  66819. }
  66820. }
  66821. };
  66822. ShadowGenerator.prototype._applyFilterValues = function () {
  66823. if (!this._shadowMap) {
  66824. return;
  66825. }
  66826. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66827. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66828. }
  66829. else {
  66830. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66831. }
  66832. };
  66833. /**
  66834. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66835. * @param onCompiled Callback triggered at the and of the effects compilation
  66836. * @param options Sets of optional options forcing the compilation with different modes
  66837. */
  66838. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66839. var _this = this;
  66840. var localOptions = __assign({ useInstances: false }, options);
  66841. var shadowMap = this.getShadowMap();
  66842. if (!shadowMap) {
  66843. if (onCompiled) {
  66844. onCompiled(this);
  66845. }
  66846. return;
  66847. }
  66848. var renderList = shadowMap.renderList;
  66849. if (!renderList) {
  66850. if (onCompiled) {
  66851. onCompiled(this);
  66852. }
  66853. return;
  66854. }
  66855. var subMeshes = new Array();
  66856. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66857. var mesh = renderList_1[_i];
  66858. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66859. }
  66860. if (subMeshes.length === 0) {
  66861. if (onCompiled) {
  66862. onCompiled(this);
  66863. }
  66864. return;
  66865. }
  66866. var currentIndex = 0;
  66867. var checkReady = function () {
  66868. if (!_this._scene || !_this._scene.getEngine()) {
  66869. return;
  66870. }
  66871. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66872. currentIndex++;
  66873. if (currentIndex >= subMeshes.length) {
  66874. if (onCompiled) {
  66875. onCompiled(_this);
  66876. }
  66877. return;
  66878. }
  66879. }
  66880. setTimeout(checkReady, 16);
  66881. };
  66882. checkReady();
  66883. };
  66884. /**
  66885. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66886. * @param options Sets of optional options forcing the compilation with different modes
  66887. * @returns A promise that resolves when the compilation completes
  66888. */
  66889. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66890. var _this = this;
  66891. return new Promise(function (resolve) {
  66892. _this.forceCompilation(function () {
  66893. resolve();
  66894. }, options);
  66895. });
  66896. };
  66897. /**
  66898. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66899. * @param subMesh The submesh we want to render in the shadow map
  66900. * @param useInstances Defines wether will draw in the map using instances
  66901. * @returns true if ready otherwise, false
  66902. */
  66903. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66904. var defines = [];
  66905. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66906. defines.push("#define FLOAT");
  66907. }
  66908. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66909. defines.push("#define ESM");
  66910. }
  66911. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66912. defines.push("#define DEPTHTEXTURE");
  66913. }
  66914. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66915. var mesh = subMesh.getMesh();
  66916. var material = subMesh.getMaterial();
  66917. // Normal bias.
  66918. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66919. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66920. defines.push("#define NORMAL");
  66921. if (mesh.nonUniformScaling) {
  66922. defines.push("#define NONUNIFORMSCALING");
  66923. }
  66924. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66925. defines.push("#define DIRECTIONINLIGHTDATA");
  66926. }
  66927. }
  66928. // Alpha test
  66929. if (material && material.needAlphaTesting()) {
  66930. var alphaTexture = material.getAlphaTestTexture();
  66931. if (alphaTexture) {
  66932. defines.push("#define ALPHATEST");
  66933. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66934. attribs.push(BABYLON.VertexBuffer.UVKind);
  66935. defines.push("#define UV1");
  66936. }
  66937. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66938. if (alphaTexture.coordinatesIndex === 1) {
  66939. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66940. defines.push("#define UV2");
  66941. }
  66942. }
  66943. }
  66944. }
  66945. // Bones
  66946. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66947. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66948. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66949. if (mesh.numBoneInfluencers > 4) {
  66950. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66951. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66952. }
  66953. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66954. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66955. }
  66956. else {
  66957. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66958. }
  66959. // Morph targets
  66960. var manager = mesh.morphTargetManager;
  66961. var morphInfluencers = 0;
  66962. if (manager) {
  66963. if (manager.numInfluencers > 0) {
  66964. defines.push("#define MORPHTARGETS");
  66965. morphInfluencers = manager.numInfluencers;
  66966. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66967. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66968. }
  66969. }
  66970. // Instances
  66971. if (useInstances) {
  66972. defines.push("#define INSTANCES");
  66973. attribs.push("world0");
  66974. attribs.push("world1");
  66975. attribs.push("world2");
  66976. attribs.push("world3");
  66977. }
  66978. // Get correct effect
  66979. var join = defines.join("\n");
  66980. if (this._cachedDefines !== join) {
  66981. this._cachedDefines = join;
  66982. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66983. }
  66984. if (!this._effect.isReady()) {
  66985. return false;
  66986. }
  66987. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66988. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66989. this._initializeBlurRTTAndPostProcesses();
  66990. }
  66991. }
  66992. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66993. return false;
  66994. }
  66995. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66996. return false;
  66997. }
  66998. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66999. return false;
  67000. }
  67001. return true;
  67002. };
  67003. /**
  67004. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  67005. * @param defines Defines of the material we want to update
  67006. * @param lightIndex Index of the light in the enabled light list of the material
  67007. */
  67008. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  67009. var scene = this._scene;
  67010. var light = this._light;
  67011. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67012. return;
  67013. }
  67014. defines["SHADOW" + lightIndex] = true;
  67015. if (this.useContactHardeningShadow) {
  67016. defines["SHADOWPCSS" + lightIndex] = true;
  67017. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67018. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67019. }
  67020. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67021. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67022. }
  67023. // else default to high.
  67024. }
  67025. if (this.usePercentageCloserFiltering) {
  67026. defines["SHADOWPCF" + lightIndex] = true;
  67027. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67028. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67029. }
  67030. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67031. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67032. }
  67033. // else default to high.
  67034. }
  67035. else if (this.usePoissonSampling) {
  67036. defines["SHADOWPOISSON" + lightIndex] = true;
  67037. }
  67038. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  67039. defines["SHADOWESM" + lightIndex] = true;
  67040. }
  67041. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67042. defines["SHADOWCLOSEESM" + lightIndex] = true;
  67043. }
  67044. if (light.needCube()) {
  67045. defines["SHADOWCUBE" + lightIndex] = true;
  67046. }
  67047. };
  67048. /**
  67049. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  67050. * defined in the generator but impacting the effect).
  67051. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  67052. * @param effect The effect we are binfing the information for
  67053. */
  67054. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  67055. var light = this._light;
  67056. var scene = this._scene;
  67057. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67058. return;
  67059. }
  67060. var camera = scene.activeCamera;
  67061. if (!camera) {
  67062. return;
  67063. }
  67064. var shadowMap = this.getShadowMap();
  67065. if (!shadowMap) {
  67066. return;
  67067. }
  67068. if (!light.needCube()) {
  67069. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  67070. }
  67071. // Only PCF uses depth stencil texture.
  67072. if (this._filter === ShadowGenerator.FILTER_PCF) {
  67073. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67074. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67075. }
  67076. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  67077. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67078. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  67079. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67080. }
  67081. else {
  67082. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67083. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  67084. }
  67085. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  67086. };
  67087. /**
  67088. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  67089. * (eq to shadow prjection matrix * light transform matrix)
  67090. * @returns The transform matrix used to create the shadow map
  67091. */
  67092. ShadowGenerator.prototype.getTransformMatrix = function () {
  67093. var scene = this._scene;
  67094. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  67095. return this._transformMatrix;
  67096. }
  67097. this._currentRenderID = scene.getRenderId();
  67098. this._currentFaceIndexCache = this._currentFaceIndex;
  67099. var lightPosition = this._light.position;
  67100. if (this._light.computeTransformedInformation()) {
  67101. lightPosition = this._light.transformedPosition;
  67102. }
  67103. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  67104. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  67105. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  67106. }
  67107. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  67108. this._cachedPosition.copyFrom(lightPosition);
  67109. this._cachedDirection.copyFrom(this._lightDirection);
  67110. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  67111. var shadowMap = this.getShadowMap();
  67112. if (shadowMap) {
  67113. var renderList = shadowMap.renderList;
  67114. if (renderList) {
  67115. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  67116. }
  67117. }
  67118. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  67119. }
  67120. return this._transformMatrix;
  67121. };
  67122. /**
  67123. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  67124. * Cube and 2D textures for instance.
  67125. */
  67126. ShadowGenerator.prototype.recreateShadowMap = function () {
  67127. var shadowMap = this._shadowMap;
  67128. if (!shadowMap) {
  67129. return;
  67130. }
  67131. // Track render list.
  67132. var renderList = shadowMap.renderList;
  67133. // Clean up existing data.
  67134. this._disposeRTTandPostProcesses();
  67135. // Reinitializes.
  67136. this._initializeGenerator();
  67137. // Reaffect the filter to ensure a correct fallback if necessary.
  67138. this.filter = this.filter;
  67139. // Reaffect the filter.
  67140. this._applyFilterValues();
  67141. // Reaffect Render List.
  67142. this._shadowMap.renderList = renderList;
  67143. };
  67144. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  67145. if (this._shadowMap2) {
  67146. this._shadowMap2.dispose();
  67147. this._shadowMap2 = null;
  67148. }
  67149. if (this._boxBlurPostprocess) {
  67150. this._boxBlurPostprocess.dispose();
  67151. this._boxBlurPostprocess = null;
  67152. }
  67153. if (this._kernelBlurXPostprocess) {
  67154. this._kernelBlurXPostprocess.dispose();
  67155. this._kernelBlurXPostprocess = null;
  67156. }
  67157. if (this._kernelBlurYPostprocess) {
  67158. this._kernelBlurYPostprocess.dispose();
  67159. this._kernelBlurYPostprocess = null;
  67160. }
  67161. this._blurPostProcesses = [];
  67162. };
  67163. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  67164. if (this._shadowMap) {
  67165. this._shadowMap.dispose();
  67166. this._shadowMap = null;
  67167. }
  67168. this._disposeBlurPostProcesses();
  67169. };
  67170. /**
  67171. * Disposes the ShadowGenerator.
  67172. * Returns nothing.
  67173. */
  67174. ShadowGenerator.prototype.dispose = function () {
  67175. this._disposeRTTandPostProcesses();
  67176. if (this._light) {
  67177. this._light._shadowGenerator = null;
  67178. this._light._markMeshesAsLightDirty();
  67179. }
  67180. };
  67181. /**
  67182. * Serializes the shadow generator setup to a json object.
  67183. * @returns The serialized JSON object
  67184. */
  67185. ShadowGenerator.prototype.serialize = function () {
  67186. var serializationObject = {};
  67187. var shadowMap = this.getShadowMap();
  67188. if (!shadowMap) {
  67189. return serializationObject;
  67190. }
  67191. serializationObject.lightId = this._light.id;
  67192. serializationObject.mapSize = shadowMap.getRenderSize();
  67193. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  67194. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  67195. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67196. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67197. serializationObject.usePoissonSampling = this.usePoissonSampling;
  67198. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  67199. serializationObject.depthScale = this.depthScale;
  67200. serializationObject.darkness = this.getDarkness();
  67201. serializationObject.blurBoxOffset = this.blurBoxOffset;
  67202. serializationObject.blurKernel = this.blurKernel;
  67203. serializationObject.blurScale = this.blurScale;
  67204. serializationObject.useKernelBlur = this.useKernelBlur;
  67205. serializationObject.transparencyShadow = this._transparencyShadow;
  67206. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  67207. serializationObject.bias = this.bias;
  67208. serializationObject.normalBias = this.normalBias;
  67209. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  67210. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  67211. serializationObject.filteringQuality = this.filteringQuality;
  67212. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  67213. serializationObject.renderList = [];
  67214. if (shadowMap.renderList) {
  67215. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  67216. var mesh = shadowMap.renderList[meshIndex];
  67217. serializationObject.renderList.push(mesh.id);
  67218. }
  67219. }
  67220. return serializationObject;
  67221. };
  67222. /**
  67223. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  67224. * @param parsedShadowGenerator The JSON object to parse
  67225. * @param scene The scene to create the shadow map for
  67226. * @returns The parsed shadow generator
  67227. */
  67228. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  67229. //casting to point light, as light is missing the position attr and typescript complains.
  67230. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  67231. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  67232. var shadowMap = shadowGenerator.getShadowMap();
  67233. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  67234. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67235. meshes.forEach(function (mesh) {
  67236. if (!shadowMap) {
  67237. return;
  67238. }
  67239. if (!shadowMap.renderList) {
  67240. shadowMap.renderList = [];
  67241. }
  67242. shadowMap.renderList.push(mesh);
  67243. });
  67244. }
  67245. if (parsedShadowGenerator.usePoissonSampling) {
  67246. shadowGenerator.usePoissonSampling = true;
  67247. }
  67248. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67249. shadowGenerator.useExponentialShadowMap = true;
  67250. }
  67251. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67252. shadowGenerator.useBlurExponentialShadowMap = true;
  67253. }
  67254. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67255. shadowGenerator.useCloseExponentialShadowMap = true;
  67256. }
  67257. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67258. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67259. }
  67260. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67261. shadowGenerator.usePercentageCloserFiltering = true;
  67262. }
  67263. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67264. shadowGenerator.useContactHardeningShadow = true;
  67265. }
  67266. if (parsedShadowGenerator.filteringQuality) {
  67267. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67268. }
  67269. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67270. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67271. }
  67272. // Backward compat
  67273. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67274. shadowGenerator.useExponentialShadowMap = true;
  67275. }
  67276. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67277. shadowGenerator.useBlurExponentialShadowMap = true;
  67278. }
  67279. if (parsedShadowGenerator.depthScale) {
  67280. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67281. }
  67282. if (parsedShadowGenerator.blurScale) {
  67283. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67284. }
  67285. if (parsedShadowGenerator.blurBoxOffset) {
  67286. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67287. }
  67288. if (parsedShadowGenerator.useKernelBlur) {
  67289. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67290. }
  67291. if (parsedShadowGenerator.blurKernel) {
  67292. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67293. }
  67294. if (parsedShadowGenerator.bias !== undefined) {
  67295. shadowGenerator.bias = parsedShadowGenerator.bias;
  67296. }
  67297. if (parsedShadowGenerator.normalBias !== undefined) {
  67298. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67299. }
  67300. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  67301. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  67302. }
  67303. if (parsedShadowGenerator.darkness) {
  67304. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67305. }
  67306. if (parsedShadowGenerator.transparencyShadow) {
  67307. shadowGenerator.setTransparencyShadow(true);
  67308. }
  67309. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67310. return shadowGenerator;
  67311. };
  67312. /**
  67313. * Shadow generator mode None: no filtering applied.
  67314. */
  67315. ShadowGenerator.FILTER_NONE = 0;
  67316. /**
  67317. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67318. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67319. */
  67320. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67321. /**
  67322. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67323. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67324. */
  67325. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67326. /**
  67327. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67328. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67329. */
  67330. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67331. /**
  67332. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67333. * edge artifacts on steep falloff.
  67334. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67335. */
  67336. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67337. /**
  67338. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67339. * edge artifacts on steep falloff.
  67340. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67341. */
  67342. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67343. /**
  67344. * Shadow generator mode PCF: Percentage Closer Filtering
  67345. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67346. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67347. */
  67348. ShadowGenerator.FILTER_PCF = 6;
  67349. /**
  67350. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67351. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67352. * Contact Hardening
  67353. */
  67354. ShadowGenerator.FILTER_PCSS = 7;
  67355. /**
  67356. * Reserved for PCF and PCSS
  67357. * Highest Quality.
  67358. *
  67359. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67360. *
  67361. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67362. */
  67363. ShadowGenerator.QUALITY_HIGH = 0;
  67364. /**
  67365. * Reserved for PCF and PCSS
  67366. * Good tradeoff for quality/perf cross devices
  67367. *
  67368. * Execute PCF on a 3*3 kernel.
  67369. *
  67370. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67371. */
  67372. ShadowGenerator.QUALITY_MEDIUM = 1;
  67373. /**
  67374. * Reserved for PCF and PCSS
  67375. * The lowest quality but the fastest.
  67376. *
  67377. * Execute PCF on a 1*1 kernel.
  67378. *
  67379. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67380. */
  67381. ShadowGenerator.QUALITY_LOW = 2;
  67382. return ShadowGenerator;
  67383. }());
  67384. BABYLON.ShadowGenerator = ShadowGenerator;
  67385. })(BABYLON || (BABYLON = {}));
  67386. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67387. var BABYLON;
  67388. (function (BABYLON) {
  67389. var DefaultLoadingScreen = /** @class */ (function () {
  67390. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67391. if (_loadingText === void 0) { _loadingText = ""; }
  67392. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67393. var _this = this;
  67394. this._renderingCanvas = _renderingCanvas;
  67395. this._loadingText = _loadingText;
  67396. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67397. // Resize
  67398. this._resizeLoadingUI = function () {
  67399. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67400. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67401. if (!_this._loadingDiv) {
  67402. return;
  67403. }
  67404. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67405. _this._loadingDiv.style.left = canvasRect.left + "px";
  67406. _this._loadingDiv.style.top = canvasRect.top + "px";
  67407. _this._loadingDiv.style.width = canvasRect.width + "px";
  67408. _this._loadingDiv.style.height = canvasRect.height + "px";
  67409. };
  67410. }
  67411. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67412. if (this._loadingDiv) {
  67413. // Do not add a loading screen if there is already one
  67414. return;
  67415. }
  67416. this._loadingDiv = document.createElement("div");
  67417. this._loadingDiv.id = "babylonjsLoadingDiv";
  67418. this._loadingDiv.style.opacity = "0";
  67419. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67420. this._loadingDiv.style.pointerEvents = "none";
  67421. // Loading text
  67422. this._loadingTextDiv = document.createElement("div");
  67423. this._loadingTextDiv.style.position = "absolute";
  67424. this._loadingTextDiv.style.left = "0";
  67425. this._loadingTextDiv.style.top = "50%";
  67426. this._loadingTextDiv.style.marginTop = "80px";
  67427. this._loadingTextDiv.style.width = "100%";
  67428. this._loadingTextDiv.style.height = "20px";
  67429. this._loadingTextDiv.style.fontFamily = "Arial";
  67430. this._loadingTextDiv.style.fontSize = "14px";
  67431. this._loadingTextDiv.style.color = "white";
  67432. this._loadingTextDiv.style.textAlign = "center";
  67433. this._loadingTextDiv.innerHTML = "Loading";
  67434. this._loadingDiv.appendChild(this._loadingTextDiv);
  67435. //set the predefined text
  67436. this._loadingTextDiv.innerHTML = this._loadingText;
  67437. // Generating keyframes
  67438. var style = document.createElement('style');
  67439. style.type = 'text/css';
  67440. 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 }";
  67441. style.innerHTML = keyFrames;
  67442. document.getElementsByTagName('head')[0].appendChild(style);
  67443. // Loading img
  67444. var imgBack = new Image();
  67445. 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";
  67446. imgBack.style.position = "absolute";
  67447. imgBack.style.left = "50%";
  67448. imgBack.style.top = "50%";
  67449. imgBack.style.marginLeft = "-60px";
  67450. imgBack.style.marginTop = "-60px";
  67451. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67452. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67453. imgBack.style.transformOrigin = "50% 50%";
  67454. imgBack.style.webkitTransformOrigin = "50% 50%";
  67455. this._loadingDiv.appendChild(imgBack);
  67456. this._resizeLoadingUI();
  67457. window.addEventListener("resize", this._resizeLoadingUI);
  67458. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67459. document.body.appendChild(this._loadingDiv);
  67460. this._loadingDiv.style.opacity = "1";
  67461. };
  67462. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67463. var _this = this;
  67464. if (!this._loadingDiv) {
  67465. return;
  67466. }
  67467. var onTransitionEnd = function () {
  67468. if (!_this._loadingDiv) {
  67469. return;
  67470. }
  67471. document.body.removeChild(_this._loadingDiv);
  67472. window.removeEventListener("resize", _this._resizeLoadingUI);
  67473. _this._loadingDiv = null;
  67474. };
  67475. this._loadingDiv.style.opacity = "0";
  67476. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67477. };
  67478. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67479. set: function (text) {
  67480. this._loadingText = text;
  67481. if (this._loadingTextDiv) {
  67482. this._loadingTextDiv.innerHTML = this._loadingText;
  67483. }
  67484. },
  67485. enumerable: true,
  67486. configurable: true
  67487. });
  67488. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67489. get: function () {
  67490. return this._loadingDivBackgroundColor;
  67491. },
  67492. set: function (color) {
  67493. this._loadingDivBackgroundColor = color;
  67494. if (!this._loadingDiv) {
  67495. return;
  67496. }
  67497. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67498. },
  67499. enumerable: true,
  67500. configurable: true
  67501. });
  67502. return DefaultLoadingScreen;
  67503. }());
  67504. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67505. })(BABYLON || (BABYLON = {}));
  67506. //# sourceMappingURL=babylon.loadingScreen.js.map
  67507. var BABYLON;
  67508. (function (BABYLON) {
  67509. var SceneLoaderProgressEvent = /** @class */ (function () {
  67510. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67511. this.lengthComputable = lengthComputable;
  67512. this.loaded = loaded;
  67513. this.total = total;
  67514. }
  67515. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67516. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67517. };
  67518. return SceneLoaderProgressEvent;
  67519. }());
  67520. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67521. var SceneLoader = /** @class */ (function () {
  67522. function SceneLoader() {
  67523. }
  67524. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67525. get: function () {
  67526. return 0;
  67527. },
  67528. enumerable: true,
  67529. configurable: true
  67530. });
  67531. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67532. get: function () {
  67533. return 1;
  67534. },
  67535. enumerable: true,
  67536. configurable: true
  67537. });
  67538. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67539. get: function () {
  67540. return 2;
  67541. },
  67542. enumerable: true,
  67543. configurable: true
  67544. });
  67545. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67546. get: function () {
  67547. return 3;
  67548. },
  67549. enumerable: true,
  67550. configurable: true
  67551. });
  67552. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67553. get: function () {
  67554. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67555. },
  67556. set: function (value) {
  67557. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67558. },
  67559. enumerable: true,
  67560. configurable: true
  67561. });
  67562. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67563. get: function () {
  67564. return SceneLoader._ShowLoadingScreen;
  67565. },
  67566. set: function (value) {
  67567. SceneLoader._ShowLoadingScreen = value;
  67568. },
  67569. enumerable: true,
  67570. configurable: true
  67571. });
  67572. Object.defineProperty(SceneLoader, "loggingLevel", {
  67573. get: function () {
  67574. return SceneLoader._loggingLevel;
  67575. },
  67576. set: function (value) {
  67577. SceneLoader._loggingLevel = value;
  67578. },
  67579. enumerable: true,
  67580. configurable: true
  67581. });
  67582. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67583. get: function () {
  67584. return SceneLoader._CleanBoneMatrixWeights;
  67585. },
  67586. set: function (value) {
  67587. SceneLoader._CleanBoneMatrixWeights = value;
  67588. },
  67589. enumerable: true,
  67590. configurable: true
  67591. });
  67592. SceneLoader._getDefaultPlugin = function () {
  67593. return SceneLoader._registeredPlugins[".babylon"];
  67594. };
  67595. SceneLoader._getPluginForExtension = function (extension) {
  67596. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67597. if (registeredPlugin) {
  67598. return registeredPlugin;
  67599. }
  67600. 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");
  67601. return SceneLoader._getDefaultPlugin();
  67602. };
  67603. SceneLoader._getPluginForDirectLoad = function (data) {
  67604. for (var extension in SceneLoader._registeredPlugins) {
  67605. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67606. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67607. return SceneLoader._registeredPlugins[extension];
  67608. }
  67609. }
  67610. return SceneLoader._getDefaultPlugin();
  67611. };
  67612. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67613. if (sceneFilename.name) {
  67614. sceneFilename = sceneFilename.name;
  67615. }
  67616. var queryStringPosition = sceneFilename.indexOf("?");
  67617. if (queryStringPosition !== -1) {
  67618. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67619. }
  67620. var dotPosition = sceneFilename.lastIndexOf(".");
  67621. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67622. return SceneLoader._getPluginForExtension(extension);
  67623. };
  67624. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67625. SceneLoader._getDirectLoad = function (sceneFilename) {
  67626. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67627. return sceneFilename.substr(5);
  67628. }
  67629. return null;
  67630. };
  67631. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67632. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67633. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67634. var plugin;
  67635. if (registeredPlugin.plugin.createPlugin) {
  67636. plugin = registeredPlugin.plugin.createPlugin();
  67637. }
  67638. else {
  67639. plugin = registeredPlugin.plugin;
  67640. }
  67641. var useArrayBuffer = registeredPlugin.isBinary;
  67642. var database;
  67643. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67644. var dataCallback = function (data, responseURL) {
  67645. if (scene.isDisposed) {
  67646. onError("Scene has been disposed");
  67647. return;
  67648. }
  67649. scene.database = database;
  67650. onSuccess(plugin, data, responseURL);
  67651. };
  67652. var request = null;
  67653. var pluginDisposed = false;
  67654. var onDisposeObservable = plugin.onDisposeObservable;
  67655. if (onDisposeObservable) {
  67656. onDisposeObservable.add(function () {
  67657. pluginDisposed = true;
  67658. if (request) {
  67659. request.abort();
  67660. request = null;
  67661. }
  67662. onDispose();
  67663. });
  67664. }
  67665. var manifestChecked = function () {
  67666. if (pluginDisposed) {
  67667. return;
  67668. }
  67669. var url = rootUrl + sceneFilename;
  67670. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67671. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67672. } : undefined, database, useArrayBuffer, function (request, exception) {
  67673. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67674. });
  67675. };
  67676. if (directLoad) {
  67677. dataCallback(directLoad);
  67678. return plugin;
  67679. }
  67680. if (rootUrl.indexOf("file:") === -1) {
  67681. var engine = scene.getEngine();
  67682. var canUseOfflineSupport = engine.enableOfflineSupport;
  67683. if (canUseOfflineSupport) {
  67684. // Also check for exceptions
  67685. var exceptionFound = false;
  67686. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67687. var regex = _a[_i];
  67688. if (regex.test(rootUrl + sceneFilename)) {
  67689. exceptionFound = true;
  67690. break;
  67691. }
  67692. }
  67693. canUseOfflineSupport = !exceptionFound;
  67694. }
  67695. if (canUseOfflineSupport) {
  67696. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67697. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67698. }
  67699. else {
  67700. manifestChecked();
  67701. }
  67702. }
  67703. // Loading file from disk via input file or drag'n'drop
  67704. else {
  67705. var fileOrString = sceneFilename;
  67706. if (fileOrString.name) { // File
  67707. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67708. }
  67709. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67710. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67711. }
  67712. else {
  67713. onError("Unable to find file named " + sceneFilename);
  67714. }
  67715. }
  67716. return plugin;
  67717. };
  67718. // Public functions
  67719. SceneLoader.GetPluginForExtension = function (extension) {
  67720. return SceneLoader._getPluginForExtension(extension).plugin;
  67721. };
  67722. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67723. return !!SceneLoader._registeredPlugins[extension];
  67724. };
  67725. SceneLoader.RegisterPlugin = function (plugin) {
  67726. if (typeof plugin.extensions === "string") {
  67727. var extension = plugin.extensions;
  67728. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67729. plugin: plugin,
  67730. isBinary: false
  67731. };
  67732. }
  67733. else {
  67734. var extensions = plugin.extensions;
  67735. Object.keys(extensions).forEach(function (extension) {
  67736. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67737. plugin: plugin,
  67738. isBinary: extensions[extension].isBinary
  67739. };
  67740. });
  67741. }
  67742. };
  67743. /**
  67744. * Import meshes into a scene
  67745. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67746. * @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)
  67747. * @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)
  67748. * @param scene the instance of BABYLON.Scene to append to
  67749. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67750. * @param onProgress a callback with a progress event for each file being loaded
  67751. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67752. * @param pluginExtension the extension used to determine the plugin
  67753. * @returns The loaded plugin
  67754. */
  67755. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67756. if (sceneFilename === void 0) { sceneFilename = ""; }
  67757. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67758. if (onSuccess === void 0) { onSuccess = null; }
  67759. if (onProgress === void 0) { onProgress = null; }
  67760. if (onError === void 0) { onError = null; }
  67761. if (pluginExtension === void 0) { pluginExtension = null; }
  67762. if (!scene) {
  67763. BABYLON.Tools.Error("No scene available to import mesh to");
  67764. return null;
  67765. }
  67766. if (!sceneFilename) {
  67767. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67768. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67769. }
  67770. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67771. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67772. return null;
  67773. }
  67774. var loadingToken = {};
  67775. scene._addPendingData(loadingToken);
  67776. var disposeHandler = function () {
  67777. scene._removePendingData(loadingToken);
  67778. };
  67779. var errorHandler = function (message, exception) {
  67780. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67781. if (onError) {
  67782. onError(scene, errorMessage, exception);
  67783. }
  67784. else {
  67785. BABYLON.Tools.Error(errorMessage);
  67786. // should the exception be thrown?
  67787. }
  67788. disposeHandler();
  67789. };
  67790. var progressHandler = onProgress ? function (event) {
  67791. try {
  67792. onProgress(event);
  67793. }
  67794. catch (e) {
  67795. errorHandler("Error in onProgress callback", e);
  67796. }
  67797. } : undefined;
  67798. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67799. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67800. if (onSuccess) {
  67801. try {
  67802. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67803. }
  67804. catch (e) {
  67805. errorHandler("Error in onSuccess callback", e);
  67806. }
  67807. }
  67808. scene._removePendingData(loadingToken);
  67809. };
  67810. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67811. if (plugin.rewriteRootURL) {
  67812. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67813. }
  67814. if (sceneFilename === "") {
  67815. if (sceneFilename === "") {
  67816. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67817. }
  67818. }
  67819. if (plugin.importMesh) {
  67820. var syncedPlugin = plugin;
  67821. var meshes = new Array();
  67822. var particleSystems = new Array();
  67823. var skeletons = new Array();
  67824. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67825. return;
  67826. }
  67827. scene.loadingPluginName = plugin.name;
  67828. successHandler(meshes, particleSystems, skeletons, []);
  67829. }
  67830. else {
  67831. var asyncedPlugin = plugin;
  67832. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67833. scene.loadingPluginName = plugin.name;
  67834. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67835. }).catch(function (error) {
  67836. errorHandler(error.message, error);
  67837. });
  67838. }
  67839. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67840. };
  67841. /**
  67842. * Import meshes into a scene
  67843. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67844. * @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)
  67845. * @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)
  67846. * @param scene the instance of BABYLON.Scene to append to
  67847. * @param onProgress a callback with a progress event for each file being loaded
  67848. * @param pluginExtension the extension used to determine the plugin
  67849. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67850. */
  67851. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67852. if (sceneFilename === void 0) { sceneFilename = ""; }
  67853. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67854. if (onProgress === void 0) { onProgress = null; }
  67855. if (pluginExtension === void 0) { pluginExtension = null; }
  67856. return new Promise(function (resolve, reject) {
  67857. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67858. resolve({
  67859. meshes: meshes,
  67860. particleSystems: particleSystems,
  67861. skeletons: skeletons,
  67862. animationGroups: animationGroups
  67863. });
  67864. }, onProgress, function (scene, message, exception) {
  67865. reject(exception || new Error(message));
  67866. }, pluginExtension);
  67867. });
  67868. };
  67869. /**
  67870. * Load a scene
  67871. * @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)
  67872. * @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)
  67873. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67874. * @param onSuccess a callback with the scene when import succeeds
  67875. * @param onProgress a callback with a progress event for each file being loaded
  67876. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67877. * @param pluginExtension the extension used to determine the plugin
  67878. * @returns The loaded plugin
  67879. */
  67880. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67881. if (onSuccess === void 0) { onSuccess = null; }
  67882. if (onProgress === void 0) { onProgress = null; }
  67883. if (onError === void 0) { onError = null; }
  67884. if (pluginExtension === void 0) { pluginExtension = null; }
  67885. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67886. };
  67887. /**
  67888. * Load a scene
  67889. * @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)
  67890. * @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)
  67891. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67892. * @param onProgress a callback with a progress event for each file being loaded
  67893. * @param pluginExtension the extension used to determine the plugin
  67894. * @returns The loaded scene
  67895. */
  67896. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67897. if (onProgress === void 0) { onProgress = null; }
  67898. if (pluginExtension === void 0) { pluginExtension = null; }
  67899. return new Promise(function (resolve, reject) {
  67900. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67901. resolve(scene);
  67902. }, onProgress, function (scene, message, exception) {
  67903. reject(exception || new Error(message));
  67904. }, pluginExtension);
  67905. });
  67906. };
  67907. /**
  67908. * Append a scene
  67909. * @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)
  67910. * @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)
  67911. * @param scene is the instance of BABYLON.Scene to append to
  67912. * @param onSuccess a callback with the scene when import succeeds
  67913. * @param onProgress a callback with a progress event for each file being loaded
  67914. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67915. * @param pluginExtension the extension used to determine the plugin
  67916. * @returns The loaded plugin
  67917. */
  67918. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67919. if (sceneFilename === void 0) { sceneFilename = ""; }
  67920. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67921. if (onSuccess === void 0) { onSuccess = null; }
  67922. if (onProgress === void 0) { onProgress = null; }
  67923. if (onError === void 0) { onError = null; }
  67924. if (pluginExtension === void 0) { pluginExtension = null; }
  67925. if (!scene) {
  67926. BABYLON.Tools.Error("No scene available to append to");
  67927. return null;
  67928. }
  67929. if (!sceneFilename) {
  67930. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67931. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67932. }
  67933. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67934. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67935. return null;
  67936. }
  67937. if (SceneLoader.ShowLoadingScreen) {
  67938. scene.getEngine().displayLoadingUI();
  67939. }
  67940. var loadingToken = {};
  67941. scene._addPendingData(loadingToken);
  67942. var disposeHandler = function () {
  67943. scene._removePendingData(loadingToken);
  67944. scene.getEngine().hideLoadingUI();
  67945. };
  67946. var errorHandler = function (message, exception) {
  67947. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67948. if (onError) {
  67949. onError(scene, errorMessage, exception);
  67950. }
  67951. else {
  67952. BABYLON.Tools.Error(errorMessage);
  67953. // should the exception be thrown?
  67954. }
  67955. disposeHandler();
  67956. };
  67957. var progressHandler = onProgress ? function (event) {
  67958. try {
  67959. onProgress(event);
  67960. }
  67961. catch (e) {
  67962. errorHandler("Error in onProgress callback", e);
  67963. }
  67964. } : undefined;
  67965. var successHandler = function () {
  67966. if (onSuccess) {
  67967. try {
  67968. onSuccess(scene);
  67969. }
  67970. catch (e) {
  67971. errorHandler("Error in onSuccess callback", e);
  67972. }
  67973. }
  67974. scene._removePendingData(loadingToken);
  67975. };
  67976. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67977. if (sceneFilename === "") {
  67978. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67979. }
  67980. if (plugin.load) {
  67981. var syncedPlugin = plugin;
  67982. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67983. return;
  67984. }
  67985. scene.loadingPluginName = plugin.name;
  67986. successHandler();
  67987. }
  67988. else {
  67989. var asyncedPlugin = plugin;
  67990. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67991. scene.loadingPluginName = plugin.name;
  67992. successHandler();
  67993. }).catch(function (error) {
  67994. errorHandler(error.message, error);
  67995. });
  67996. }
  67997. if (SceneLoader.ShowLoadingScreen) {
  67998. scene.executeWhenReady(function () {
  67999. scene.getEngine().hideLoadingUI();
  68000. });
  68001. }
  68002. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68003. };
  68004. /**
  68005. * Append a scene
  68006. * @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)
  68007. * @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)
  68008. * @param scene is the instance of BABYLON.Scene to append to
  68009. * @param onProgress a callback with a progress event for each file being loaded
  68010. * @param pluginExtension the extension used to determine the plugin
  68011. * @returns The given scene
  68012. */
  68013. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68014. if (sceneFilename === void 0) { sceneFilename = ""; }
  68015. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68016. if (onProgress === void 0) { onProgress = null; }
  68017. if (pluginExtension === void 0) { pluginExtension = null; }
  68018. return new Promise(function (resolve, reject) {
  68019. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  68020. resolve(scene);
  68021. }, onProgress, function (scene, message, exception) {
  68022. reject(exception || new Error(message));
  68023. }, pluginExtension);
  68024. });
  68025. };
  68026. /**
  68027. * Load a scene into an asset container
  68028. * @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)
  68029. * @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)
  68030. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  68031. * @param onSuccess a callback with the scene when import succeeds
  68032. * @param onProgress a callback with a progress event for each file being loaded
  68033. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68034. * @param pluginExtension the extension used to determine the plugin
  68035. * @returns The loaded plugin
  68036. */
  68037. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68038. if (sceneFilename === void 0) { sceneFilename = ""; }
  68039. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68040. if (onSuccess === void 0) { onSuccess = null; }
  68041. if (onProgress === void 0) { onProgress = null; }
  68042. if (onError === void 0) { onError = null; }
  68043. if (pluginExtension === void 0) { pluginExtension = null; }
  68044. if (!scene) {
  68045. BABYLON.Tools.Error("No scene available to load asset container to");
  68046. return null;
  68047. }
  68048. if (!sceneFilename) {
  68049. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68050. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68051. }
  68052. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68053. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68054. return null;
  68055. }
  68056. var loadingToken = {};
  68057. scene._addPendingData(loadingToken);
  68058. var disposeHandler = function () {
  68059. scene._removePendingData(loadingToken);
  68060. };
  68061. var errorHandler = function (message, exception) {
  68062. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68063. if (onError) {
  68064. onError(scene, errorMessage, exception);
  68065. }
  68066. else {
  68067. BABYLON.Tools.Error(errorMessage);
  68068. // should the exception be thrown?
  68069. }
  68070. disposeHandler();
  68071. };
  68072. var progressHandler = onProgress ? function (event) {
  68073. try {
  68074. onProgress(event);
  68075. }
  68076. catch (e) {
  68077. errorHandler("Error in onProgress callback", e);
  68078. }
  68079. } : undefined;
  68080. var successHandler = function (assets) {
  68081. if (onSuccess) {
  68082. try {
  68083. onSuccess(assets);
  68084. }
  68085. catch (e) {
  68086. errorHandler("Error in onSuccess callback", e);
  68087. }
  68088. }
  68089. scene._removePendingData(loadingToken);
  68090. };
  68091. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68092. if (plugin.loadAssetContainer) {
  68093. var syncedPlugin = plugin;
  68094. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  68095. if (!assetContainer) {
  68096. return;
  68097. }
  68098. scene.loadingPluginName = plugin.name;
  68099. successHandler(assetContainer);
  68100. }
  68101. else if (plugin.loadAssetContainerAsync) {
  68102. var asyncedPlugin = plugin;
  68103. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  68104. scene.loadingPluginName = plugin.name;
  68105. successHandler(assetContainer);
  68106. }).catch(function (error) {
  68107. errorHandler(error.message, error);
  68108. });
  68109. }
  68110. else {
  68111. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  68112. }
  68113. if (SceneLoader.ShowLoadingScreen) {
  68114. scene.executeWhenReady(function () {
  68115. scene.getEngine().hideLoadingUI();
  68116. });
  68117. }
  68118. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68119. };
  68120. /**
  68121. * Load a scene into an asset container
  68122. * @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)
  68123. * @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)
  68124. * @param scene is the instance of BABYLON.Scene to append to
  68125. * @param onProgress a callback with a progress event for each file being loaded
  68126. * @param pluginExtension the extension used to determine the plugin
  68127. * @returns The loaded asset container
  68128. */
  68129. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68130. if (sceneFilename === void 0) { sceneFilename = ""; }
  68131. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68132. if (onProgress === void 0) { onProgress = null; }
  68133. if (pluginExtension === void 0) { pluginExtension = null; }
  68134. return new Promise(function (resolve, reject) {
  68135. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  68136. resolve(assetContainer);
  68137. }, onProgress, function (scene, message, exception) {
  68138. reject(exception || new Error(message));
  68139. }, pluginExtension);
  68140. });
  68141. };
  68142. // Flags
  68143. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  68144. SceneLoader._ShowLoadingScreen = true;
  68145. SceneLoader._CleanBoneMatrixWeights = false;
  68146. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  68147. // Members
  68148. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  68149. SceneLoader._registeredPlugins = {};
  68150. return SceneLoader;
  68151. }());
  68152. BABYLON.SceneLoader = SceneLoader;
  68153. ;
  68154. })(BABYLON || (BABYLON = {}));
  68155. //# sourceMappingURL=babylon.sceneLoader.js.map
  68156. var BABYLON;
  68157. (function (BABYLON) {
  68158. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  68159. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68160. var parsedMaterial = parsedData.materials[index];
  68161. if (parsedMaterial.id === id) {
  68162. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68163. }
  68164. }
  68165. return null;
  68166. };
  68167. var isDescendantOf = function (mesh, names, hierarchyIds) {
  68168. for (var i in names) {
  68169. if (mesh.name === names[i]) {
  68170. hierarchyIds.push(mesh.id);
  68171. return true;
  68172. }
  68173. }
  68174. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  68175. hierarchyIds.push(mesh.id);
  68176. return true;
  68177. }
  68178. return false;
  68179. };
  68180. var logOperation = function (operation, producer) {
  68181. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  68182. };
  68183. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  68184. if (addToScene === void 0) { addToScene = false; }
  68185. var container = new BABYLON.AssetContainer(scene);
  68186. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68187. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68188. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68189. // and avoid problems with multiple concurrent .babylon loads.
  68190. var log = "importScene has failed JSON parse";
  68191. try {
  68192. var parsedData = JSON.parse(data);
  68193. log = "";
  68194. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68195. var index;
  68196. var cache;
  68197. // Lights
  68198. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  68199. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  68200. var parsedLight = parsedData.lights[index];
  68201. var light = BABYLON.Light.Parse(parsedLight, scene);
  68202. if (light) {
  68203. container.lights.push(light);
  68204. log += (index === 0 ? "\n\tLights:" : "");
  68205. log += "\n\t\t" + light.toString(fullDetails);
  68206. }
  68207. }
  68208. }
  68209. // Animations
  68210. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  68211. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  68212. var parsedAnimation = parsedData.animations[index];
  68213. var animation = BABYLON.Animation.Parse(parsedAnimation);
  68214. scene.animations.push(animation);
  68215. container.animations.push(animation);
  68216. log += (index === 0 ? "\n\tAnimations:" : "");
  68217. log += "\n\t\t" + animation.toString(fullDetails);
  68218. }
  68219. }
  68220. // Materials
  68221. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  68222. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68223. var parsedMaterial = parsedData.materials[index];
  68224. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68225. container.materials.push(mat);
  68226. log += (index === 0 ? "\n\tMaterials:" : "");
  68227. log += "\n\t\t" + mat.toString(fullDetails);
  68228. }
  68229. }
  68230. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68231. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  68232. var parsedMultiMaterial = parsedData.multiMaterials[index];
  68233. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68234. container.multiMaterials.push(mmat);
  68235. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68236. log += "\n\t\t" + mmat.toString(fullDetails);
  68237. }
  68238. }
  68239. // Morph targets
  68240. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68241. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68242. var managerData = _a[_i];
  68243. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68244. }
  68245. }
  68246. // Skeletons
  68247. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68248. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68249. var parsedSkeleton = parsedData.skeletons[index];
  68250. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68251. container.skeletons.push(skeleton);
  68252. log += (index === 0 ? "\n\tSkeletons:" : "");
  68253. log += "\n\t\t" + skeleton.toString(fullDetails);
  68254. }
  68255. }
  68256. // Geometries
  68257. var geometries = parsedData.geometries;
  68258. if (geometries !== undefined && geometries !== null) {
  68259. var addedGeometry = new Array();
  68260. // Boxes
  68261. var boxes = geometries.boxes;
  68262. if (boxes !== undefined && boxes !== null) {
  68263. for (index = 0, cache = boxes.length; index < cache; index++) {
  68264. var parsedBox = boxes[index];
  68265. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68266. }
  68267. }
  68268. // Spheres
  68269. var spheres = geometries.spheres;
  68270. if (spheres !== undefined && spheres !== null) {
  68271. for (index = 0, cache = spheres.length; index < cache; index++) {
  68272. var parsedSphere = spheres[index];
  68273. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68274. }
  68275. }
  68276. // Cylinders
  68277. var cylinders = geometries.cylinders;
  68278. if (cylinders !== undefined && cylinders !== null) {
  68279. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68280. var parsedCylinder = cylinders[index];
  68281. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68282. }
  68283. }
  68284. // Toruses
  68285. var toruses = geometries.toruses;
  68286. if (toruses !== undefined && toruses !== null) {
  68287. for (index = 0, cache = toruses.length; index < cache; index++) {
  68288. var parsedTorus = toruses[index];
  68289. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68290. }
  68291. }
  68292. // Grounds
  68293. var grounds = geometries.grounds;
  68294. if (grounds !== undefined && grounds !== null) {
  68295. for (index = 0, cache = grounds.length; index < cache; index++) {
  68296. var parsedGround = grounds[index];
  68297. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68298. }
  68299. }
  68300. // Planes
  68301. var planes = geometries.planes;
  68302. if (planes !== undefined && planes !== null) {
  68303. for (index = 0, cache = planes.length; index < cache; index++) {
  68304. var parsedPlane = planes[index];
  68305. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68306. }
  68307. }
  68308. // TorusKnots
  68309. var torusKnots = geometries.torusKnots;
  68310. if (torusKnots !== undefined && torusKnots !== null) {
  68311. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68312. var parsedTorusKnot = torusKnots[index];
  68313. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68314. }
  68315. }
  68316. // VertexData
  68317. var vertexData = geometries.vertexData;
  68318. if (vertexData !== undefined && vertexData !== null) {
  68319. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68320. var parsedVertexData = vertexData[index];
  68321. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68322. }
  68323. }
  68324. addedGeometry.forEach(function (g) {
  68325. if (g) {
  68326. container.geometries.push(g);
  68327. }
  68328. });
  68329. }
  68330. // Transform nodes
  68331. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68332. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68333. var parsedTransformNode = parsedData.transformNodes[index];
  68334. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68335. container.transformNodes.push(node);
  68336. }
  68337. }
  68338. // Meshes
  68339. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68340. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68341. var parsedMesh = parsedData.meshes[index];
  68342. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68343. container.meshes.push(mesh);
  68344. log += (index === 0 ? "\n\tMeshes:" : "");
  68345. log += "\n\t\t" + mesh.toString(fullDetails);
  68346. }
  68347. }
  68348. // Cameras
  68349. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68350. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68351. var parsedCamera = parsedData.cameras[index];
  68352. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68353. container.cameras.push(camera);
  68354. log += (index === 0 ? "\n\tCameras:" : "");
  68355. log += "\n\t\t" + camera.toString(fullDetails);
  68356. }
  68357. }
  68358. // Browsing all the graph to connect the dots
  68359. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68360. var camera = scene.cameras[index];
  68361. if (camera._waitingParentId) {
  68362. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68363. camera._waitingParentId = null;
  68364. }
  68365. }
  68366. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68367. var light_1 = scene.lights[index];
  68368. if (light_1 && light_1._waitingParentId) {
  68369. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68370. light_1._waitingParentId = null;
  68371. }
  68372. }
  68373. // Sounds
  68374. // TODO: add sound
  68375. var loadedSounds = [];
  68376. var loadedSound;
  68377. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68378. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68379. var parsedSound = parsedData.sounds[index];
  68380. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68381. if (!parsedSound.url)
  68382. parsedSound.url = parsedSound.name;
  68383. if (!loadedSounds[parsedSound.url]) {
  68384. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68385. loadedSounds[parsedSound.url] = loadedSound;
  68386. container.sounds.push(loadedSound);
  68387. }
  68388. else {
  68389. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68390. }
  68391. }
  68392. else {
  68393. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68394. }
  68395. }
  68396. }
  68397. loadedSounds = [];
  68398. // Connect parents & children and parse actions
  68399. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68400. var transformNode = scene.transformNodes[index];
  68401. if (transformNode._waitingParentId) {
  68402. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68403. transformNode._waitingParentId = null;
  68404. }
  68405. }
  68406. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68407. var mesh = scene.meshes[index];
  68408. if (mesh._waitingParentId) {
  68409. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68410. mesh._waitingParentId = null;
  68411. }
  68412. if (mesh._waitingActions) {
  68413. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68414. mesh._waitingActions = null;
  68415. }
  68416. }
  68417. // freeze world matrix application
  68418. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68419. var currentMesh = scene.meshes[index];
  68420. if (currentMesh._waitingFreezeWorldMatrix) {
  68421. currentMesh.freezeWorldMatrix();
  68422. currentMesh._waitingFreezeWorldMatrix = null;
  68423. }
  68424. else {
  68425. currentMesh.computeWorldMatrix(true);
  68426. }
  68427. }
  68428. // Shadows
  68429. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68430. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68431. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68432. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68433. // SG would be available on their associated lights
  68434. }
  68435. }
  68436. // Lights exclusions / inclusions
  68437. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68438. var light_2 = scene.lights[index];
  68439. // Excluded check
  68440. if (light_2._excludedMeshesIds.length > 0) {
  68441. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68442. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68443. if (excludedMesh) {
  68444. light_2.excludedMeshes.push(excludedMesh);
  68445. }
  68446. }
  68447. light_2._excludedMeshesIds = [];
  68448. }
  68449. // Included check
  68450. if (light_2._includedOnlyMeshesIds.length > 0) {
  68451. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68452. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68453. if (includedOnlyMesh) {
  68454. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68455. }
  68456. }
  68457. light_2._includedOnlyMeshesIds = [];
  68458. }
  68459. }
  68460. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  68461. // Actions (scene)
  68462. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68463. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68464. }
  68465. if (!addToScene) {
  68466. container.removeAllFromScene();
  68467. }
  68468. }
  68469. catch (err) {
  68470. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68471. if (onError) {
  68472. onError(msg, err);
  68473. }
  68474. else {
  68475. BABYLON.Tools.Log(msg);
  68476. throw err;
  68477. }
  68478. }
  68479. finally {
  68480. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68481. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68482. }
  68483. }
  68484. return container;
  68485. };
  68486. BABYLON.SceneLoader.RegisterPlugin({
  68487. name: "babylon.js",
  68488. extensions: ".babylon",
  68489. canDirectLoad: function (data) {
  68490. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68491. return true;
  68492. }
  68493. return false;
  68494. },
  68495. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68496. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68497. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68498. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68499. // and avoid problems with multiple concurrent .babylon loads.
  68500. var log = "importMesh has failed JSON parse";
  68501. try {
  68502. var parsedData = JSON.parse(data);
  68503. log = "";
  68504. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68505. if (!meshesNames) {
  68506. meshesNames = null;
  68507. }
  68508. else if (!Array.isArray(meshesNames)) {
  68509. meshesNames = [meshesNames];
  68510. }
  68511. var hierarchyIds = new Array();
  68512. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68513. var loadedSkeletonsIds = [];
  68514. var loadedMaterialsIds = [];
  68515. var index;
  68516. var cache;
  68517. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68518. var parsedMesh = parsedData.meshes[index];
  68519. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68520. if (meshesNames !== null) {
  68521. // Remove found mesh name from list.
  68522. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68523. }
  68524. //Geometry?
  68525. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68526. //does the file contain geometries?
  68527. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68528. //find the correct geometry and add it to the scene
  68529. var found = false;
  68530. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68531. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68532. return;
  68533. }
  68534. else {
  68535. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68536. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68537. switch (geometryType) {
  68538. case "boxes":
  68539. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68540. break;
  68541. case "spheres":
  68542. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68543. break;
  68544. case "cylinders":
  68545. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68546. break;
  68547. case "toruses":
  68548. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68549. break;
  68550. case "grounds":
  68551. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68552. break;
  68553. case "planes":
  68554. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68555. break;
  68556. case "torusKnots":
  68557. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68558. break;
  68559. case "vertexData":
  68560. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68561. break;
  68562. }
  68563. found = true;
  68564. }
  68565. });
  68566. }
  68567. });
  68568. if (found === false) {
  68569. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68570. }
  68571. }
  68572. }
  68573. // Material ?
  68574. if (parsedMesh.materialId) {
  68575. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68576. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68577. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68578. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68579. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68580. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68581. var subMatId = parsedMultiMaterial.materials[matIndex];
  68582. loadedMaterialsIds.push(subMatId);
  68583. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68584. if (mat) {
  68585. log += "\n\tMaterial " + mat.toString(fullDetails);
  68586. }
  68587. }
  68588. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68589. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68590. if (mmat) {
  68591. materialFound = true;
  68592. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68593. }
  68594. break;
  68595. }
  68596. }
  68597. }
  68598. if (materialFound === false) {
  68599. loadedMaterialsIds.push(parsedMesh.materialId);
  68600. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68601. if (!mat) {
  68602. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68603. }
  68604. else {
  68605. log += "\n\tMaterial " + mat.toString(fullDetails);
  68606. }
  68607. }
  68608. }
  68609. // Skeleton ?
  68610. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68611. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68612. if (skeletonAlreadyLoaded === false) {
  68613. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68614. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68615. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68616. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68617. skeletons.push(skeleton);
  68618. loadedSkeletonsIds.push(parsedSkeleton.id);
  68619. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68620. }
  68621. }
  68622. }
  68623. }
  68624. // Morph targets ?
  68625. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68626. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68627. var managerData = _a[_i];
  68628. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68629. }
  68630. }
  68631. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68632. meshes.push(mesh);
  68633. log += "\n\tMesh " + mesh.toString(fullDetails);
  68634. }
  68635. }
  68636. // Connecting parents
  68637. var currentMesh;
  68638. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68639. currentMesh = scene.meshes[index];
  68640. if (currentMesh._waitingParentId) {
  68641. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68642. currentMesh._waitingParentId = null;
  68643. }
  68644. }
  68645. // freeze and compute world matrix application
  68646. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68647. currentMesh = scene.meshes[index];
  68648. if (currentMesh._waitingFreezeWorldMatrix) {
  68649. currentMesh.freezeWorldMatrix();
  68650. currentMesh._waitingFreezeWorldMatrix = null;
  68651. }
  68652. else {
  68653. currentMesh.computeWorldMatrix(true);
  68654. }
  68655. }
  68656. }
  68657. // Particles
  68658. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68659. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  68660. if (parser) {
  68661. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68662. var parsedParticleSystem = parsedData.particleSystems[index];
  68663. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68664. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  68665. }
  68666. }
  68667. }
  68668. }
  68669. return true;
  68670. }
  68671. catch (err) {
  68672. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68673. if (onError) {
  68674. onError(msg, err);
  68675. }
  68676. else {
  68677. BABYLON.Tools.Log(msg);
  68678. throw err;
  68679. }
  68680. }
  68681. finally {
  68682. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68683. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68684. }
  68685. }
  68686. return false;
  68687. },
  68688. load: function (scene, data, rootUrl, onError) {
  68689. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68690. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68691. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68692. // and avoid problems with multiple concurrent .babylon loads.
  68693. var log = "importScene has failed JSON parse";
  68694. try {
  68695. var parsedData = JSON.parse(data);
  68696. log = "";
  68697. // Scene
  68698. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68699. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68700. }
  68701. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68702. scene.autoClear = parsedData.autoClear;
  68703. }
  68704. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68705. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68706. }
  68707. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68708. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68709. }
  68710. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68711. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68712. }
  68713. // Fog
  68714. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68715. scene.fogMode = parsedData.fogMode;
  68716. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68717. scene.fogStart = parsedData.fogStart;
  68718. scene.fogEnd = parsedData.fogEnd;
  68719. scene.fogDensity = parsedData.fogDensity;
  68720. log += "\tFog mode for scene: ";
  68721. switch (scene.fogMode) {
  68722. // getters not compiling, so using hardcoded
  68723. case 1:
  68724. log += "exp\n";
  68725. break;
  68726. case 2:
  68727. log += "exp2\n";
  68728. break;
  68729. case 3:
  68730. log += "linear\n";
  68731. break;
  68732. }
  68733. }
  68734. //Physics
  68735. if (parsedData.physicsEnabled) {
  68736. var physicsPlugin;
  68737. if (parsedData.physicsEngine === "cannon") {
  68738. physicsPlugin = new BABYLON.CannonJSPlugin();
  68739. }
  68740. else if (parsedData.physicsEngine === "oimo") {
  68741. physicsPlugin = new BABYLON.OimoJSPlugin();
  68742. }
  68743. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68744. //else - default engine, which is currently oimo
  68745. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68746. scene.enablePhysics(physicsGravity, physicsPlugin);
  68747. }
  68748. // Metadata
  68749. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68750. scene.metadata = parsedData.metadata;
  68751. }
  68752. //collisions, if defined. otherwise, default is true
  68753. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68754. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68755. }
  68756. scene.workerCollisions = !!parsedData.workerCollisions;
  68757. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68758. if (!container) {
  68759. return false;
  68760. }
  68761. if (parsedData.autoAnimate) {
  68762. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68763. }
  68764. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68765. scene.setActiveCameraByID(parsedData.activeCameraID);
  68766. }
  68767. // Environment texture
  68768. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68769. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68770. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68771. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68772. if (parsedData.environmentTextureRotationY) {
  68773. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68774. }
  68775. scene.environmentTexture = hdrTexture;
  68776. }
  68777. else {
  68778. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68779. if (parsedData.environmentTextureRotationY) {
  68780. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68781. }
  68782. scene.environmentTexture = cubeTexture;
  68783. }
  68784. if (parsedData.createDefaultSkybox === true) {
  68785. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68786. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68787. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68788. }
  68789. }
  68790. // Finish
  68791. return true;
  68792. }
  68793. catch (err) {
  68794. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68795. if (onError) {
  68796. onError(msg, err);
  68797. }
  68798. else {
  68799. BABYLON.Tools.Log(msg);
  68800. throw err;
  68801. }
  68802. }
  68803. finally {
  68804. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68805. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68806. }
  68807. }
  68808. return false;
  68809. },
  68810. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68811. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68812. return container;
  68813. }
  68814. });
  68815. })(BABYLON || (BABYLON = {}));
  68816. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68817. var BABYLON;
  68818. (function (BABYLON) {
  68819. var FilesInput = /** @class */ (function () {
  68820. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68821. this.onProcessFileCallback = function () { return true; };
  68822. this._engine = engine;
  68823. this._currentScene = scene;
  68824. this._sceneLoadedCallback = sceneLoadedCallback;
  68825. this._progressCallback = progressCallback;
  68826. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68827. this._textureLoadingCallback = textureLoadingCallback;
  68828. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68829. this._onReloadCallback = onReloadCallback;
  68830. this._errorCallback = errorCallback;
  68831. }
  68832. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68833. var _this = this;
  68834. if (elementToMonitor) {
  68835. this._elementToMonitor = elementToMonitor;
  68836. this._dragEnterHandler = function (e) { _this.drag(e); };
  68837. this._dragOverHandler = function (e) { _this.drag(e); };
  68838. this._dropHandler = function (e) { _this.drop(e); };
  68839. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68840. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68841. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68842. }
  68843. };
  68844. FilesInput.prototype.dispose = function () {
  68845. if (!this._elementToMonitor) {
  68846. return;
  68847. }
  68848. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68849. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68850. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68851. };
  68852. FilesInput.prototype.renderFunction = function () {
  68853. if (this._additionalRenderLoopLogicCallback) {
  68854. this._additionalRenderLoopLogicCallback();
  68855. }
  68856. if (this._currentScene) {
  68857. if (this._textureLoadingCallback) {
  68858. var remaining = this._currentScene.getWaitingItemsCount();
  68859. if (remaining > 0) {
  68860. this._textureLoadingCallback(remaining);
  68861. }
  68862. }
  68863. this._currentScene.render();
  68864. }
  68865. };
  68866. FilesInput.prototype.drag = function (e) {
  68867. e.stopPropagation();
  68868. e.preventDefault();
  68869. };
  68870. FilesInput.prototype.drop = function (eventDrop) {
  68871. eventDrop.stopPropagation();
  68872. eventDrop.preventDefault();
  68873. this.loadFiles(eventDrop);
  68874. };
  68875. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68876. var _this = this;
  68877. var reader = folder.createReader();
  68878. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68879. reader.readEntries(function (entries) {
  68880. remaining.count += entries.length;
  68881. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68882. var entry = entries_1[_i];
  68883. if (entry.isFile) {
  68884. entry.file(function (file) {
  68885. file.correctName = relativePath + file.name;
  68886. files.push(file);
  68887. if (--remaining.count === 0) {
  68888. callback();
  68889. }
  68890. });
  68891. }
  68892. else if (entry.isDirectory) {
  68893. _this._traverseFolder(entry, files, remaining, callback);
  68894. }
  68895. }
  68896. if (--remaining.count) {
  68897. callback();
  68898. }
  68899. });
  68900. };
  68901. FilesInput.prototype._processFiles = function (files) {
  68902. for (var i = 0; i < files.length; i++) {
  68903. var name = files[i].correctName.toLowerCase();
  68904. var extension = name.split('.').pop();
  68905. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68906. continue;
  68907. }
  68908. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68909. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68910. this._sceneFileToLoad = files[i];
  68911. }
  68912. else {
  68913. FilesInput.FilesToLoad[name] = files[i];
  68914. }
  68915. }
  68916. };
  68917. FilesInput.prototype.loadFiles = function (event) {
  68918. var _this = this;
  68919. if (this._startingProcessingFilesCallback)
  68920. this._startingProcessingFilesCallback();
  68921. // Handling data transfer via drag'n'drop
  68922. if (event && event.dataTransfer && event.dataTransfer.files) {
  68923. this._filesToLoad = event.dataTransfer.files;
  68924. }
  68925. // Handling files from input files
  68926. if (event && event.target && event.target.files) {
  68927. this._filesToLoad = event.target.files;
  68928. }
  68929. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68930. var files_1 = new Array();
  68931. var folders = [];
  68932. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68933. for (var i = 0; i < this._filesToLoad.length; i++) {
  68934. var fileToLoad = this._filesToLoad[i];
  68935. var name_1 = fileToLoad.name.toLowerCase();
  68936. var entry = void 0;
  68937. fileToLoad.correctName = name_1;
  68938. if (items) {
  68939. var item = items[i];
  68940. if (item.getAsEntry) {
  68941. entry = item.getAsEntry();
  68942. }
  68943. else if (item.webkitGetAsEntry) {
  68944. entry = item.webkitGetAsEntry();
  68945. }
  68946. }
  68947. if (!entry) {
  68948. files_1.push(fileToLoad);
  68949. }
  68950. else {
  68951. if (entry.isDirectory) {
  68952. folders.push(entry);
  68953. }
  68954. else {
  68955. files_1.push(fileToLoad);
  68956. }
  68957. }
  68958. }
  68959. if (folders.length === 0) {
  68960. this._processFiles(files_1);
  68961. this._processReload();
  68962. }
  68963. else {
  68964. var remaining = { count: folders.length };
  68965. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68966. var folder = folders_1[_i];
  68967. this._traverseFolder(folder, files_1, remaining, function () {
  68968. _this._processFiles(files_1);
  68969. if (remaining.count === 0) {
  68970. _this._processReload();
  68971. }
  68972. });
  68973. }
  68974. }
  68975. }
  68976. };
  68977. FilesInput.prototype._processReload = function () {
  68978. if (this._onReloadCallback) {
  68979. this._onReloadCallback(this._sceneFileToLoad);
  68980. }
  68981. else {
  68982. this.reload();
  68983. }
  68984. };
  68985. FilesInput.prototype.reload = function () {
  68986. var _this = this;
  68987. // If a scene file has been provided
  68988. if (this._sceneFileToLoad) {
  68989. if (this._currentScene) {
  68990. if (BABYLON.Tools.errorsCount > 0) {
  68991. BABYLON.Tools.ClearLogCache();
  68992. }
  68993. this._engine.stopRenderLoop();
  68994. }
  68995. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68996. if (_this._progressCallback) {
  68997. _this._progressCallback(progress);
  68998. }
  68999. }).then(function (scene) {
  69000. if (_this._currentScene) {
  69001. _this._currentScene.dispose();
  69002. }
  69003. _this._currentScene = scene;
  69004. if (_this._sceneLoadedCallback) {
  69005. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  69006. }
  69007. // Wait for textures and shaders to be ready
  69008. _this._currentScene.executeWhenReady(function () {
  69009. _this._engine.runRenderLoop(function () {
  69010. _this.renderFunction();
  69011. });
  69012. });
  69013. }).catch(function (error) {
  69014. if (_this._errorCallback) {
  69015. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  69016. }
  69017. });
  69018. }
  69019. else {
  69020. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  69021. }
  69022. };
  69023. FilesInput.FilesToLoad = {};
  69024. return FilesInput;
  69025. }());
  69026. BABYLON.FilesInput = FilesInput;
  69027. })(BABYLON || (BABYLON = {}));
  69028. //# sourceMappingURL=babylon.filesInput.js.map
  69029. var BABYLON;
  69030. (function (BABYLON) {
  69031. /**
  69032. * This class implement a typical dictionary using a string as key and the generic type T as value.
  69033. * The underlying implementation relies on an associative array to ensure the best performances.
  69034. * The value can be anything including 'null' but except 'undefined'
  69035. */
  69036. var StringDictionary = /** @class */ (function () {
  69037. function StringDictionary() {
  69038. this._count = 0;
  69039. this._data = {};
  69040. }
  69041. /**
  69042. * This will clear this dictionary and copy the content from the 'source' one.
  69043. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  69044. * @param source the dictionary to take the content from and copy to this dictionary
  69045. */
  69046. StringDictionary.prototype.copyFrom = function (source) {
  69047. var _this = this;
  69048. this.clear();
  69049. source.forEach(function (t, v) { return _this.add(t, v); });
  69050. };
  69051. /**
  69052. * Get a value based from its key
  69053. * @param key the given key to get the matching value from
  69054. * @return the value if found, otherwise undefined is returned
  69055. */
  69056. StringDictionary.prototype.get = function (key) {
  69057. var val = this._data[key];
  69058. if (val !== undefined) {
  69059. return val;
  69060. }
  69061. return undefined;
  69062. };
  69063. /**
  69064. * Get a value from its key or add it if it doesn't exist.
  69065. * This method will ensure you that a given key/data will be present in the dictionary.
  69066. * @param key the given key to get the matching value from
  69067. * @param factory the factory that will create the value if the key is not present in the dictionary.
  69068. * The factory will only be invoked if there's no data for the given key.
  69069. * @return the value corresponding to the key.
  69070. */
  69071. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  69072. var val = this.get(key);
  69073. if (val !== undefined) {
  69074. return val;
  69075. }
  69076. val = factory(key);
  69077. if (val) {
  69078. this.add(key, val);
  69079. }
  69080. return val;
  69081. };
  69082. /**
  69083. * Get a value from its key if present in the dictionary otherwise add it
  69084. * @param key the key to get the value from
  69085. * @param val if there's no such key/value pair in the dictionary add it with this value
  69086. * @return the value corresponding to the key
  69087. */
  69088. StringDictionary.prototype.getOrAdd = function (key, val) {
  69089. var curVal = this.get(key);
  69090. if (curVal !== undefined) {
  69091. return curVal;
  69092. }
  69093. this.add(key, val);
  69094. return val;
  69095. };
  69096. /**
  69097. * Check if there's a given key in the dictionary
  69098. * @param key the key to check for
  69099. * @return true if the key is present, false otherwise
  69100. */
  69101. StringDictionary.prototype.contains = function (key) {
  69102. return this._data[key] !== undefined;
  69103. };
  69104. /**
  69105. * Add a new key and its corresponding value
  69106. * @param key the key to add
  69107. * @param value the value corresponding to the key
  69108. * @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
  69109. */
  69110. StringDictionary.prototype.add = function (key, value) {
  69111. if (this._data[key] !== undefined) {
  69112. return false;
  69113. }
  69114. this._data[key] = value;
  69115. ++this._count;
  69116. return true;
  69117. };
  69118. StringDictionary.prototype.set = function (key, value) {
  69119. if (this._data[key] === undefined) {
  69120. return false;
  69121. }
  69122. this._data[key] = value;
  69123. return true;
  69124. };
  69125. /**
  69126. * Get the element of the given key and remove it from the dictionary
  69127. * @param key
  69128. */
  69129. StringDictionary.prototype.getAndRemove = function (key) {
  69130. var val = this.get(key);
  69131. if (val !== undefined) {
  69132. delete this._data[key];
  69133. --this._count;
  69134. return val;
  69135. }
  69136. return null;
  69137. };
  69138. /**
  69139. * Remove a key/value from the dictionary.
  69140. * @param key the key to remove
  69141. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  69142. */
  69143. StringDictionary.prototype.remove = function (key) {
  69144. if (this.contains(key)) {
  69145. delete this._data[key];
  69146. --this._count;
  69147. return true;
  69148. }
  69149. return false;
  69150. };
  69151. /**
  69152. * Clear the whole content of the dictionary
  69153. */
  69154. StringDictionary.prototype.clear = function () {
  69155. this._data = {};
  69156. this._count = 0;
  69157. };
  69158. Object.defineProperty(StringDictionary.prototype, "count", {
  69159. get: function () {
  69160. return this._count;
  69161. },
  69162. enumerable: true,
  69163. configurable: true
  69164. });
  69165. /**
  69166. * Execute a callback on each key/val of the dictionary.
  69167. * Note that you can remove any element in this dictionary in the callback implementation
  69168. * @param callback the callback to execute on a given key/value pair
  69169. */
  69170. StringDictionary.prototype.forEach = function (callback) {
  69171. for (var cur in this._data) {
  69172. var val = this._data[cur];
  69173. callback(cur, val);
  69174. }
  69175. };
  69176. /**
  69177. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  69178. * If the callback returns null or undefined the method will iterate to the next key/value pair
  69179. * Note that you can remove any element in this dictionary in the callback implementation
  69180. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  69181. */
  69182. StringDictionary.prototype.first = function (callback) {
  69183. for (var cur in this._data) {
  69184. var val = this._data[cur];
  69185. var res = callback(cur, val);
  69186. if (res) {
  69187. return res;
  69188. }
  69189. }
  69190. return null;
  69191. };
  69192. return StringDictionary;
  69193. }());
  69194. BABYLON.StringDictionary = StringDictionary;
  69195. })(BABYLON || (BABYLON = {}));
  69196. //# sourceMappingURL=babylon.stringDictionary.js.map
  69197. var BABYLON;
  69198. (function (BABYLON) {
  69199. var Tags = /** @class */ (function () {
  69200. function Tags() {
  69201. }
  69202. Tags.EnableFor = function (obj) {
  69203. obj._tags = obj._tags || {};
  69204. obj.hasTags = function () {
  69205. return Tags.HasTags(obj);
  69206. };
  69207. obj.addTags = function (tagsString) {
  69208. return Tags.AddTagsTo(obj, tagsString);
  69209. };
  69210. obj.removeTags = function (tagsString) {
  69211. return Tags.RemoveTagsFrom(obj, tagsString);
  69212. };
  69213. obj.matchesTagsQuery = function (tagsQuery) {
  69214. return Tags.MatchesQuery(obj, tagsQuery);
  69215. };
  69216. };
  69217. Tags.DisableFor = function (obj) {
  69218. delete obj._tags;
  69219. delete obj.hasTags;
  69220. delete obj.addTags;
  69221. delete obj.removeTags;
  69222. delete obj.matchesTagsQuery;
  69223. };
  69224. Tags.HasTags = function (obj) {
  69225. if (!obj._tags) {
  69226. return false;
  69227. }
  69228. return !BABYLON.Tools.IsEmpty(obj._tags);
  69229. };
  69230. Tags.GetTags = function (obj, asString) {
  69231. if (asString === void 0) { asString = true; }
  69232. if (!obj._tags) {
  69233. return null;
  69234. }
  69235. if (asString) {
  69236. var tagsArray = [];
  69237. for (var tag in obj._tags) {
  69238. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69239. tagsArray.push(tag);
  69240. }
  69241. }
  69242. return tagsArray.join(" ");
  69243. }
  69244. else {
  69245. return obj._tags;
  69246. }
  69247. };
  69248. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69249. // a tag cannot start with '||', '&&', and '!'
  69250. // it cannot contain whitespaces
  69251. Tags.AddTagsTo = function (obj, tagsString) {
  69252. if (!tagsString) {
  69253. return;
  69254. }
  69255. if (typeof tagsString !== "string") {
  69256. return;
  69257. }
  69258. var tags = tagsString.split(" ");
  69259. tags.forEach(function (tag, index, array) {
  69260. Tags._AddTagTo(obj, tag);
  69261. });
  69262. };
  69263. Tags._AddTagTo = function (obj, tag) {
  69264. tag = tag.trim();
  69265. if (tag === "" || tag === "true" || tag === "false") {
  69266. return;
  69267. }
  69268. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69269. return;
  69270. }
  69271. Tags.EnableFor(obj);
  69272. obj._tags[tag] = true;
  69273. };
  69274. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69275. if (!Tags.HasTags(obj)) {
  69276. return;
  69277. }
  69278. var tags = tagsString.split(" ");
  69279. for (var t in tags) {
  69280. Tags._RemoveTagFrom(obj, tags[t]);
  69281. }
  69282. };
  69283. Tags._RemoveTagFrom = function (obj, tag) {
  69284. delete obj._tags[tag];
  69285. };
  69286. Tags.MatchesQuery = function (obj, tagsQuery) {
  69287. if (tagsQuery === undefined) {
  69288. return true;
  69289. }
  69290. if (tagsQuery === "") {
  69291. return Tags.HasTags(obj);
  69292. }
  69293. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69294. };
  69295. return Tags;
  69296. }());
  69297. BABYLON.Tags = Tags;
  69298. })(BABYLON || (BABYLON = {}));
  69299. //# sourceMappingURL=babylon.tags.js.map
  69300. var BABYLON;
  69301. (function (BABYLON) {
  69302. /**
  69303. * Class used to evalaute queries containing `and` and `or` operators
  69304. */
  69305. var AndOrNotEvaluator = /** @class */ (function () {
  69306. function AndOrNotEvaluator() {
  69307. }
  69308. /**
  69309. * Evaluate a query
  69310. * @param query defines the query to evaluate
  69311. * @param evaluateCallback defines the callback used to filter result
  69312. * @returns true if the query matches
  69313. */
  69314. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69315. if (!query.match(/\([^\(\)]*\)/g)) {
  69316. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69317. }
  69318. else {
  69319. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69320. // remove parenthesis
  69321. r = r.slice(1, r.length - 1);
  69322. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69323. });
  69324. }
  69325. if (query === "true") {
  69326. return true;
  69327. }
  69328. if (query === "false") {
  69329. return false;
  69330. }
  69331. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69332. };
  69333. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69334. evaluateCallback = evaluateCallback || (function (r) {
  69335. return r === "true" ? true : false;
  69336. });
  69337. var result;
  69338. var or = parenthesisContent.split("||");
  69339. for (var i in or) {
  69340. if (or.hasOwnProperty(i)) {
  69341. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69342. var and = ori.split("&&");
  69343. if (and.length > 1) {
  69344. for (var j = 0; j < and.length; ++j) {
  69345. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69346. if (andj !== "true" && andj !== "false") {
  69347. if (andj[0] === "!") {
  69348. result = !evaluateCallback(andj.substring(1));
  69349. }
  69350. else {
  69351. result = evaluateCallback(andj);
  69352. }
  69353. }
  69354. else {
  69355. result = andj === "true" ? true : false;
  69356. }
  69357. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69358. ori = "false";
  69359. break;
  69360. }
  69361. }
  69362. }
  69363. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69364. result = true;
  69365. break;
  69366. }
  69367. // result equals false (or undefined)
  69368. if (ori !== "true" && ori !== "false") {
  69369. if (ori[0] === "!") {
  69370. result = !evaluateCallback(ori.substring(1));
  69371. }
  69372. else {
  69373. result = evaluateCallback(ori);
  69374. }
  69375. }
  69376. else {
  69377. result = ori === "true" ? true : false;
  69378. }
  69379. }
  69380. }
  69381. // the whole parenthesis scope is replaced by 'true' or 'false'
  69382. return result ? "true" : "false";
  69383. };
  69384. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69385. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69386. // remove whitespaces
  69387. r = r.replace(/[\s]/g, function () { return ""; });
  69388. return r.length % 2 ? "!" : "";
  69389. });
  69390. booleanString = booleanString.trim();
  69391. if (booleanString === "!true") {
  69392. booleanString = "false";
  69393. }
  69394. else if (booleanString === "!false") {
  69395. booleanString = "true";
  69396. }
  69397. return booleanString;
  69398. };
  69399. return AndOrNotEvaluator;
  69400. }());
  69401. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69402. })(BABYLON || (BABYLON = {}));
  69403. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69404. var BABYLON;
  69405. (function (BABYLON) {
  69406. /**
  69407. * Class used to enable access to IndexedDB
  69408. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69409. */
  69410. var Database = /** @class */ (function () {
  69411. /**
  69412. * Creates a new Database
  69413. * @param urlToScene defines the url to load the scene
  69414. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69415. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69416. */
  69417. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69418. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69419. var _this = this;
  69420. // Handling various flavors of prefixed version of IndexedDB
  69421. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69422. this.callbackManifestChecked = callbackManifestChecked;
  69423. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69424. this.db = null;
  69425. this._enableSceneOffline = false;
  69426. this._enableTexturesOffline = false;
  69427. this.manifestVersionFound = 0;
  69428. this.mustUpdateRessources = false;
  69429. this.hasReachedQuota = false;
  69430. if (!Database.IDBStorageEnabled) {
  69431. this.callbackManifestChecked(true);
  69432. }
  69433. else {
  69434. if (disableManifestCheck) {
  69435. this._enableSceneOffline = true;
  69436. this._enableTexturesOffline = true;
  69437. this.manifestVersionFound = 1;
  69438. BABYLON.Tools.SetImmediate(function () {
  69439. _this.callbackManifestChecked(true);
  69440. });
  69441. }
  69442. else {
  69443. this._checkManifestFile();
  69444. }
  69445. }
  69446. }
  69447. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69448. /**
  69449. * Gets a boolean indicating if scene must be saved in the database
  69450. */
  69451. get: function () {
  69452. return this._enableSceneOffline;
  69453. },
  69454. enumerable: true,
  69455. configurable: true
  69456. });
  69457. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69458. /**
  69459. * Gets a boolean indicating if textures must be saved in the database
  69460. */
  69461. get: function () {
  69462. return this._enableTexturesOffline;
  69463. },
  69464. enumerable: true,
  69465. configurable: true
  69466. });
  69467. Database.prototype._checkManifestFile = function () {
  69468. var _this = this;
  69469. var noManifestFile = function () {
  69470. _this._enableSceneOffline = false;
  69471. _this._enableTexturesOffline = false;
  69472. _this.callbackManifestChecked(false);
  69473. };
  69474. var timeStampUsed = false;
  69475. var manifestURL = this.currentSceneUrl + ".manifest";
  69476. var xhr = new XMLHttpRequest();
  69477. if (navigator.onLine) {
  69478. // Adding a timestamp to by-pass browsers' cache
  69479. timeStampUsed = true;
  69480. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69481. }
  69482. xhr.open("GET", manifestURL, true);
  69483. xhr.addEventListener("load", function () {
  69484. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69485. try {
  69486. var manifestFile = JSON.parse(xhr.response);
  69487. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69488. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69489. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69490. _this.manifestVersionFound = manifestFile.version;
  69491. }
  69492. if (_this.callbackManifestChecked) {
  69493. _this.callbackManifestChecked(true);
  69494. }
  69495. }
  69496. catch (ex) {
  69497. noManifestFile();
  69498. }
  69499. }
  69500. else {
  69501. noManifestFile();
  69502. }
  69503. }, false);
  69504. xhr.addEventListener("error", function (event) {
  69505. if (timeStampUsed) {
  69506. timeStampUsed = false;
  69507. // Let's retry without the timeStamp
  69508. // It could fail when coupled with HTML5 Offline API
  69509. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69510. xhr.open("GET", retryManifestURL, true);
  69511. xhr.send();
  69512. }
  69513. else {
  69514. noManifestFile();
  69515. }
  69516. }, false);
  69517. try {
  69518. xhr.send();
  69519. }
  69520. catch (ex) {
  69521. BABYLON.Tools.Error("Error on XHR send request.");
  69522. this.callbackManifestChecked(false);
  69523. }
  69524. };
  69525. /**
  69526. * Open the database and make it available
  69527. * @param successCallback defines the callback to call on success
  69528. * @param errorCallback defines the callback to call on error
  69529. */
  69530. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69531. var _this = this;
  69532. var handleError = function () {
  69533. _this.isSupported = false;
  69534. if (errorCallback)
  69535. errorCallback();
  69536. };
  69537. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69538. // Your browser doesn't support IndexedDB
  69539. this.isSupported = false;
  69540. if (errorCallback)
  69541. errorCallback();
  69542. }
  69543. else {
  69544. // If the DB hasn't been opened or created yet
  69545. if (!this.db) {
  69546. this.hasReachedQuota = false;
  69547. this.isSupported = true;
  69548. var request = this.idbFactory.open("babylonjs", 1);
  69549. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69550. request.onerror = function (event) {
  69551. handleError();
  69552. };
  69553. // executes when a version change transaction cannot complete due to other active transactions
  69554. request.onblocked = function (event) {
  69555. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69556. handleError();
  69557. };
  69558. // DB has been opened successfully
  69559. request.onsuccess = function (event) {
  69560. _this.db = request.result;
  69561. successCallback();
  69562. };
  69563. // Initialization of the DB. Creating Scenes & Textures stores
  69564. request.onupgradeneeded = function (event) {
  69565. _this.db = (event.target).result;
  69566. if (_this.db) {
  69567. try {
  69568. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69569. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69570. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69571. }
  69572. catch (ex) {
  69573. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69574. handleError();
  69575. }
  69576. }
  69577. };
  69578. }
  69579. // DB has already been created and opened
  69580. else {
  69581. if (successCallback)
  69582. successCallback();
  69583. }
  69584. }
  69585. };
  69586. /**
  69587. * Loads an image from the database
  69588. * @param url defines the url to load from
  69589. * @param image defines the target DOM image
  69590. */
  69591. Database.prototype.loadImageFromDB = function (url, image) {
  69592. var _this = this;
  69593. var completeURL = Database._ReturnFullUrlLocation(url);
  69594. var saveAndLoadImage = function () {
  69595. if (!_this.hasReachedQuota && _this.db !== null) {
  69596. // the texture is not yet in the DB, let's try to save it
  69597. _this._saveImageIntoDBAsync(completeURL, image);
  69598. }
  69599. // If the texture is not in the DB and we've reached the DB quota limit
  69600. // let's load it directly from the web
  69601. else {
  69602. image.src = url;
  69603. }
  69604. };
  69605. if (!this.mustUpdateRessources) {
  69606. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69607. }
  69608. // First time we're download the images or update requested in the manifest file by a version change
  69609. else {
  69610. saveAndLoadImage();
  69611. }
  69612. };
  69613. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69614. if (this.isSupported && this.db !== null) {
  69615. var texture;
  69616. var transaction = this.db.transaction(["textures"]);
  69617. transaction.onabort = function (event) {
  69618. image.src = url;
  69619. };
  69620. transaction.oncomplete = function (event) {
  69621. var blobTextureURL;
  69622. if (texture) {
  69623. var URL = window.URL || window.webkitURL;
  69624. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69625. image.onerror = function () {
  69626. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69627. image.src = url;
  69628. };
  69629. image.src = blobTextureURL;
  69630. }
  69631. else {
  69632. notInDBCallback();
  69633. }
  69634. };
  69635. var getRequest = transaction.objectStore("textures").get(url);
  69636. getRequest.onsuccess = function (event) {
  69637. texture = (event.target).result;
  69638. };
  69639. getRequest.onerror = function (event) {
  69640. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69641. image.src = url;
  69642. };
  69643. }
  69644. else {
  69645. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69646. image.src = url;
  69647. }
  69648. };
  69649. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69650. var _this = this;
  69651. if (this.isSupported) {
  69652. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69653. var generateBlobUrl = function () {
  69654. var blobTextureURL;
  69655. if (blob) {
  69656. var URL = window.URL || window.webkitURL;
  69657. try {
  69658. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69659. }
  69660. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69661. catch (ex) {
  69662. blobTextureURL = URL.createObjectURL(blob);
  69663. }
  69664. }
  69665. if (blobTextureURL) {
  69666. image.src = blobTextureURL;
  69667. }
  69668. };
  69669. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69670. var xhr = new XMLHttpRequest(), blob;
  69671. xhr.open("GET", url, true);
  69672. xhr.responseType = "blob";
  69673. xhr.addEventListener("load", function () {
  69674. if (xhr.status === 200 && _this.db) {
  69675. // Blob as response (XHR2)
  69676. blob = xhr.response;
  69677. var transaction = _this.db.transaction(["textures"], "readwrite");
  69678. // the transaction could abort because of a QuotaExceededError error
  69679. transaction.onabort = function (event) {
  69680. try {
  69681. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69682. var srcElement = (event.srcElement || event.target);
  69683. var error = srcElement.error;
  69684. if (error && error.name === "QuotaExceededError") {
  69685. _this.hasReachedQuota = true;
  69686. }
  69687. }
  69688. catch (ex) { }
  69689. generateBlobUrl();
  69690. };
  69691. transaction.oncomplete = function (event) {
  69692. generateBlobUrl();
  69693. };
  69694. var newTexture = { textureUrl: url, data: blob };
  69695. try {
  69696. // Put the blob into the dabase
  69697. var addRequest = transaction.objectStore("textures").put(newTexture);
  69698. addRequest.onsuccess = function (event) {
  69699. };
  69700. addRequest.onerror = function (event) {
  69701. generateBlobUrl();
  69702. };
  69703. }
  69704. catch (ex) {
  69705. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69706. if (ex.code === 25) {
  69707. Database.IsUASupportingBlobStorage = false;
  69708. }
  69709. image.src = url;
  69710. }
  69711. }
  69712. else {
  69713. image.src = url;
  69714. }
  69715. }, false);
  69716. xhr.addEventListener("error", function (event) {
  69717. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69718. image.src = url;
  69719. }, false);
  69720. xhr.send();
  69721. }
  69722. else {
  69723. image.src = url;
  69724. }
  69725. }
  69726. else {
  69727. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69728. image.src = url;
  69729. }
  69730. };
  69731. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69732. var _this = this;
  69733. var updateVersion = function () {
  69734. // the version is not yet in the DB or we need to update it
  69735. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69736. };
  69737. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69738. };
  69739. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69740. var _this = this;
  69741. if (this.isSupported && this.db) {
  69742. var version;
  69743. try {
  69744. var transaction = this.db.transaction(["versions"]);
  69745. transaction.oncomplete = function (event) {
  69746. if (version) {
  69747. // If the version in the JSON file is different from the version in DB
  69748. if (_this.manifestVersionFound !== version.data) {
  69749. _this.mustUpdateRessources = true;
  69750. updateInDBCallback();
  69751. }
  69752. else {
  69753. callback(version.data);
  69754. }
  69755. }
  69756. // version was not found in DB
  69757. else {
  69758. _this.mustUpdateRessources = true;
  69759. updateInDBCallback();
  69760. }
  69761. };
  69762. transaction.onabort = function (event) {
  69763. callback(-1);
  69764. };
  69765. var getRequest = transaction.objectStore("versions").get(url);
  69766. getRequest.onsuccess = function (event) {
  69767. version = (event.target).result;
  69768. };
  69769. getRequest.onerror = function (event) {
  69770. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69771. callback(-1);
  69772. };
  69773. }
  69774. catch (ex) {
  69775. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69776. callback(-1);
  69777. }
  69778. }
  69779. else {
  69780. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69781. callback(-1);
  69782. }
  69783. };
  69784. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69785. var _this = this;
  69786. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69787. try {
  69788. // Open a transaction to the database
  69789. var transaction = this.db.transaction(["versions"], "readwrite");
  69790. // the transaction could abort because of a QuotaExceededError error
  69791. transaction.onabort = function (event) {
  69792. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69793. var error = event.srcElement['error'];
  69794. if (error && error.name === "QuotaExceededError") {
  69795. _this.hasReachedQuota = true;
  69796. }
  69797. }
  69798. catch (ex) { }
  69799. callback(-1);
  69800. };
  69801. transaction.oncomplete = function (event) {
  69802. callback(_this.manifestVersionFound);
  69803. };
  69804. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69805. // Put the scene into the database
  69806. var addRequest = transaction.objectStore("versions").put(newVersion);
  69807. addRequest.onsuccess = function (event) {
  69808. };
  69809. addRequest.onerror = function (event) {
  69810. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69811. };
  69812. }
  69813. catch (ex) {
  69814. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69815. callback(-1);
  69816. }
  69817. }
  69818. else {
  69819. callback(-1);
  69820. }
  69821. };
  69822. /**
  69823. * Loads a file from database
  69824. * @param url defines the URL to load from
  69825. * @param sceneLoaded defines a callback to call on success
  69826. * @param progressCallBack defines a callback to call when progress changed
  69827. * @param errorCallback defines a callback to call on error
  69828. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69829. */
  69830. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69831. var _this = this;
  69832. var completeUrl = Database._ReturnFullUrlLocation(url);
  69833. var saveAndLoadFile = function () {
  69834. // the scene is not yet in the DB, let's try to save it
  69835. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  69836. };
  69837. this._checkVersionFromDB(completeUrl, function (version) {
  69838. if (version !== -1) {
  69839. if (!_this.mustUpdateRessources) {
  69840. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69841. }
  69842. else {
  69843. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  69844. }
  69845. }
  69846. else {
  69847. if (errorCallback) {
  69848. errorCallback();
  69849. }
  69850. }
  69851. });
  69852. };
  69853. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69854. if (this.isSupported && this.db) {
  69855. var targetStore;
  69856. if (url.indexOf(".babylon") !== -1) {
  69857. targetStore = "scenes";
  69858. }
  69859. else {
  69860. targetStore = "textures";
  69861. }
  69862. var file;
  69863. var transaction = this.db.transaction([targetStore]);
  69864. transaction.oncomplete = function (event) {
  69865. if (file) {
  69866. callback(file.data);
  69867. }
  69868. // file was not found in DB
  69869. else {
  69870. notInDBCallback();
  69871. }
  69872. };
  69873. transaction.onabort = function (event) {
  69874. notInDBCallback();
  69875. };
  69876. var getRequest = transaction.objectStore(targetStore).get(url);
  69877. getRequest.onsuccess = function (event) {
  69878. file = (event.target).result;
  69879. };
  69880. getRequest.onerror = function (event) {
  69881. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69882. notInDBCallback();
  69883. };
  69884. }
  69885. else {
  69886. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69887. callback();
  69888. }
  69889. };
  69890. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  69891. var _this = this;
  69892. if (this.isSupported) {
  69893. var targetStore;
  69894. if (url.indexOf(".babylon") !== -1) {
  69895. targetStore = "scenes";
  69896. }
  69897. else {
  69898. targetStore = "textures";
  69899. }
  69900. // Create XHR
  69901. var xhr = new XMLHttpRequest();
  69902. var fileData;
  69903. xhr.open("GET", url, true);
  69904. if (useArrayBuffer) {
  69905. xhr.responseType = "arraybuffer";
  69906. }
  69907. if (progressCallback) {
  69908. xhr.onprogress = progressCallback;
  69909. }
  69910. xhr.addEventListener("load", function () {
  69911. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  69912. // Blob as response (XHR2)
  69913. //fileData = xhr.responseText;
  69914. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69915. if (!_this.hasReachedQuota && _this.db) {
  69916. // Open a transaction to the database
  69917. var transaction = _this.db.transaction([targetStore], "readwrite");
  69918. // the transaction could abort because of a QuotaExceededError error
  69919. transaction.onabort = function (event) {
  69920. try {
  69921. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69922. var error = event.srcElement['error'];
  69923. if (error && error.name === "QuotaExceededError") {
  69924. _this.hasReachedQuota = true;
  69925. }
  69926. }
  69927. catch (ex) { }
  69928. callback(fileData);
  69929. };
  69930. transaction.oncomplete = function (event) {
  69931. callback(fileData);
  69932. };
  69933. var newFile;
  69934. if (targetStore === "scenes") {
  69935. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69936. }
  69937. else {
  69938. newFile = { textureUrl: url, data: fileData };
  69939. }
  69940. try {
  69941. // Put the scene into the database
  69942. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69943. addRequest.onsuccess = function (event) {
  69944. };
  69945. addRequest.onerror = function (event) {
  69946. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69947. };
  69948. }
  69949. catch (ex) {
  69950. callback(fileData);
  69951. }
  69952. }
  69953. else {
  69954. callback(fileData);
  69955. }
  69956. }
  69957. else {
  69958. if (xhr.status >= 400 && errorCallback) {
  69959. errorCallback(xhr);
  69960. }
  69961. else {
  69962. callback();
  69963. }
  69964. }
  69965. }, false);
  69966. xhr.addEventListener("error", function (event) {
  69967. BABYLON.Tools.Error("error on XHR request.");
  69968. callback();
  69969. }, false);
  69970. xhr.send();
  69971. }
  69972. else {
  69973. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69974. callback();
  69975. }
  69976. };
  69977. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69978. Database.IsUASupportingBlobStorage = true;
  69979. /** Gets a boolean indicating if Database storate is enabled */
  69980. Database.IDBStorageEnabled = true;
  69981. Database._ParseURL = function (url) {
  69982. var a = document.createElement('a');
  69983. a.href = url;
  69984. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69985. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69986. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69987. return absLocation;
  69988. };
  69989. Database._ReturnFullUrlLocation = function (url) {
  69990. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69991. return (Database._ParseURL(window.location.href) + url);
  69992. }
  69993. else {
  69994. return url;
  69995. }
  69996. };
  69997. return Database;
  69998. }());
  69999. BABYLON.Database = Database;
  70000. })(BABYLON || (BABYLON = {}));
  70001. //# sourceMappingURL=babylon.database.js.map
  70002. var BABYLON;
  70003. (function (BABYLON) {
  70004. var FresnelParameters = /** @class */ (function () {
  70005. function FresnelParameters() {
  70006. this._isEnabled = true;
  70007. this.leftColor = BABYLON.Color3.White();
  70008. this.rightColor = BABYLON.Color3.Black();
  70009. this.bias = 0;
  70010. this.power = 1;
  70011. }
  70012. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  70013. get: function () {
  70014. return this._isEnabled;
  70015. },
  70016. set: function (value) {
  70017. if (this._isEnabled === value) {
  70018. return;
  70019. }
  70020. this._isEnabled = value;
  70021. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  70022. },
  70023. enumerable: true,
  70024. configurable: true
  70025. });
  70026. FresnelParameters.prototype.clone = function () {
  70027. var newFresnelParameters = new FresnelParameters();
  70028. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  70029. return newFresnelParameters;
  70030. };
  70031. FresnelParameters.prototype.serialize = function () {
  70032. var serializationObject = {};
  70033. serializationObject.isEnabled = this.isEnabled;
  70034. serializationObject.leftColor = this.leftColor.asArray();
  70035. serializationObject.rightColor = this.rightColor.asArray();
  70036. serializationObject.bias = this.bias;
  70037. serializationObject.power = this.power;
  70038. return serializationObject;
  70039. };
  70040. FresnelParameters.Parse = function (parsedFresnelParameters) {
  70041. var fresnelParameters = new FresnelParameters();
  70042. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  70043. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  70044. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  70045. fresnelParameters.bias = parsedFresnelParameters.bias;
  70046. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  70047. return fresnelParameters;
  70048. };
  70049. return FresnelParameters;
  70050. }());
  70051. BABYLON.FresnelParameters = FresnelParameters;
  70052. })(BABYLON || (BABYLON = {}));
  70053. //# sourceMappingURL=babylon.fresnelParameters.js.map
  70054. var BABYLON;
  70055. (function (BABYLON) {
  70056. var MultiMaterial = /** @class */ (function (_super) {
  70057. __extends(MultiMaterial, _super);
  70058. function MultiMaterial(name, scene) {
  70059. var _this = _super.call(this, name, scene, true) || this;
  70060. scene.multiMaterials.push(_this);
  70061. _this.subMaterials = new Array();
  70062. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  70063. return _this;
  70064. }
  70065. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  70066. get: function () {
  70067. return this._subMaterials;
  70068. },
  70069. set: function (value) {
  70070. this._subMaterials = value;
  70071. this._hookArray(value);
  70072. },
  70073. enumerable: true,
  70074. configurable: true
  70075. });
  70076. MultiMaterial.prototype._hookArray = function (array) {
  70077. var _this = this;
  70078. var oldPush = array.push;
  70079. array.push = function () {
  70080. var items = [];
  70081. for (var _i = 0; _i < arguments.length; _i++) {
  70082. items[_i] = arguments[_i];
  70083. }
  70084. var result = oldPush.apply(array, items);
  70085. _this._markAllSubMeshesAsTexturesDirty();
  70086. return result;
  70087. };
  70088. var oldSplice = array.splice;
  70089. array.splice = function (index, deleteCount) {
  70090. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70091. _this._markAllSubMeshesAsTexturesDirty();
  70092. return deleted;
  70093. };
  70094. };
  70095. // Properties
  70096. MultiMaterial.prototype.getSubMaterial = function (index) {
  70097. if (index < 0 || index >= this.subMaterials.length) {
  70098. return this.getScene().defaultMaterial;
  70099. }
  70100. return this.subMaterials[index];
  70101. };
  70102. MultiMaterial.prototype.getActiveTextures = function () {
  70103. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  70104. if (subMaterial) {
  70105. return subMaterial.getActiveTextures();
  70106. }
  70107. else {
  70108. return [];
  70109. }
  70110. }));
  70111. var _a;
  70112. };
  70113. // Methods
  70114. MultiMaterial.prototype.getClassName = function () {
  70115. return "MultiMaterial";
  70116. };
  70117. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  70118. for (var index = 0; index < this.subMaterials.length; index++) {
  70119. var subMaterial = this.subMaterials[index];
  70120. if (subMaterial) {
  70121. if (subMaterial.storeEffectOnSubMeshes) {
  70122. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  70123. return false;
  70124. }
  70125. continue;
  70126. }
  70127. if (!subMaterial.isReady(mesh)) {
  70128. return false;
  70129. }
  70130. }
  70131. }
  70132. return true;
  70133. };
  70134. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  70135. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  70136. for (var index = 0; index < this.subMaterials.length; index++) {
  70137. var subMaterial = null;
  70138. var current = this.subMaterials[index];
  70139. if (cloneChildren && current) {
  70140. subMaterial = current.clone(name + "-" + current.name);
  70141. }
  70142. else {
  70143. subMaterial = this.subMaterials[index];
  70144. }
  70145. newMultiMaterial.subMaterials.push(subMaterial);
  70146. }
  70147. return newMultiMaterial;
  70148. };
  70149. MultiMaterial.prototype.serialize = function () {
  70150. var serializationObject = {};
  70151. serializationObject.name = this.name;
  70152. serializationObject.id = this.id;
  70153. if (BABYLON.Tags) {
  70154. serializationObject.tags = BABYLON.Tags.GetTags(this);
  70155. }
  70156. serializationObject.materials = [];
  70157. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  70158. var subMat = this.subMaterials[matIndex];
  70159. if (subMat) {
  70160. serializationObject.materials.push(subMat.id);
  70161. }
  70162. else {
  70163. serializationObject.materials.push(null);
  70164. }
  70165. }
  70166. return serializationObject;
  70167. };
  70168. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  70169. var scene = this.getScene();
  70170. if (!scene) {
  70171. return;
  70172. }
  70173. var index = scene.multiMaterials.indexOf(this);
  70174. if (index >= 0) {
  70175. scene.multiMaterials.splice(index, 1);
  70176. }
  70177. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  70178. };
  70179. return MultiMaterial;
  70180. }(BABYLON.Material));
  70181. BABYLON.MultiMaterial = MultiMaterial;
  70182. })(BABYLON || (BABYLON = {}));
  70183. //# sourceMappingURL=babylon.multiMaterial.js.map
  70184. var BABYLON;
  70185. (function (BABYLON) {
  70186. var FreeCameraTouchInput = /** @class */ (function () {
  70187. function FreeCameraTouchInput() {
  70188. this._offsetX = null;
  70189. this._offsetY = null;
  70190. this._pointerPressed = new Array();
  70191. this.touchAngularSensibility = 200000.0;
  70192. this.touchMoveSensibility = 250.0;
  70193. }
  70194. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70195. var _this = this;
  70196. var previousPosition = null;
  70197. if (this._pointerInput === undefined) {
  70198. this._onLostFocus = function (evt) {
  70199. _this._offsetX = null;
  70200. _this._offsetY = null;
  70201. };
  70202. this._pointerInput = function (p, s) {
  70203. var evt = p.event;
  70204. if (evt.pointerType === "mouse") {
  70205. return;
  70206. }
  70207. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70208. if (!noPreventDefault) {
  70209. evt.preventDefault();
  70210. }
  70211. _this._pointerPressed.push(evt.pointerId);
  70212. if (_this._pointerPressed.length !== 1) {
  70213. return;
  70214. }
  70215. previousPosition = {
  70216. x: evt.clientX,
  70217. y: evt.clientY
  70218. };
  70219. }
  70220. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70221. if (!noPreventDefault) {
  70222. evt.preventDefault();
  70223. }
  70224. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70225. if (index === -1) {
  70226. return;
  70227. }
  70228. _this._pointerPressed.splice(index, 1);
  70229. if (index != 0) {
  70230. return;
  70231. }
  70232. previousPosition = null;
  70233. _this._offsetX = null;
  70234. _this._offsetY = null;
  70235. }
  70236. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70237. if (!noPreventDefault) {
  70238. evt.preventDefault();
  70239. }
  70240. if (!previousPosition) {
  70241. return;
  70242. }
  70243. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70244. if (index != 0) {
  70245. return;
  70246. }
  70247. _this._offsetX = evt.clientX - previousPosition.x;
  70248. _this._offsetY = -(evt.clientY - previousPosition.y);
  70249. }
  70250. };
  70251. }
  70252. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70253. if (this._onLostFocus) {
  70254. element.addEventListener("blur", this._onLostFocus);
  70255. }
  70256. };
  70257. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70258. if (this._pointerInput && element) {
  70259. if (this._observer) {
  70260. this.camera.getScene().onPointerObservable.remove(this._observer);
  70261. this._observer = null;
  70262. }
  70263. if (this._onLostFocus) {
  70264. element.removeEventListener("blur", this._onLostFocus);
  70265. this._onLostFocus = null;
  70266. }
  70267. this._pointerPressed = [];
  70268. this._offsetX = null;
  70269. this._offsetY = null;
  70270. }
  70271. };
  70272. FreeCameraTouchInput.prototype.checkInputs = function () {
  70273. if (this._offsetX && this._offsetY) {
  70274. var camera = this.camera;
  70275. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70276. if (this._pointerPressed.length > 1) {
  70277. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70278. }
  70279. else {
  70280. var speed = camera._computeLocalCameraSpeed();
  70281. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70282. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70283. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70284. }
  70285. }
  70286. };
  70287. FreeCameraTouchInput.prototype.getClassName = function () {
  70288. return "FreeCameraTouchInput";
  70289. };
  70290. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70291. return "touch";
  70292. };
  70293. __decorate([
  70294. BABYLON.serialize()
  70295. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70296. __decorate([
  70297. BABYLON.serialize()
  70298. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70299. return FreeCameraTouchInput;
  70300. }());
  70301. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70302. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70303. })(BABYLON || (BABYLON = {}));
  70304. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70305. var BABYLON;
  70306. (function (BABYLON) {
  70307. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  70308. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  70309. });
  70310. // We're mainly based on the logic defined into the FreeCamera code
  70311. var TouchCamera = /** @class */ (function (_super) {
  70312. __extends(TouchCamera, _super);
  70313. //-- end properties for backward compatibility for inputs
  70314. function TouchCamera(name, position, scene) {
  70315. var _this = _super.call(this, name, position, scene) || this;
  70316. _this.inputs.addTouch();
  70317. _this._setupInputs();
  70318. return _this;
  70319. }
  70320. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70321. //-- Begin properties for backward compatibility for inputs
  70322. get: function () {
  70323. var touch = this.inputs.attached["touch"];
  70324. if (touch)
  70325. return touch.touchAngularSensibility;
  70326. return 0;
  70327. },
  70328. set: function (value) {
  70329. var touch = this.inputs.attached["touch"];
  70330. if (touch)
  70331. touch.touchAngularSensibility = value;
  70332. },
  70333. enumerable: true,
  70334. configurable: true
  70335. });
  70336. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70337. get: function () {
  70338. var touch = this.inputs.attached["touch"];
  70339. if (touch)
  70340. return touch.touchMoveSensibility;
  70341. return 0;
  70342. },
  70343. set: function (value) {
  70344. var touch = this.inputs.attached["touch"];
  70345. if (touch)
  70346. touch.touchMoveSensibility = value;
  70347. },
  70348. enumerable: true,
  70349. configurable: true
  70350. });
  70351. TouchCamera.prototype.getClassName = function () {
  70352. return "TouchCamera";
  70353. };
  70354. TouchCamera.prototype._setupInputs = function () {
  70355. var mouse = this.inputs.attached["mouse"];
  70356. if (mouse) {
  70357. mouse.touchEnabled = false;
  70358. }
  70359. };
  70360. return TouchCamera;
  70361. }(BABYLON.FreeCamera));
  70362. BABYLON.TouchCamera = TouchCamera;
  70363. })(BABYLON || (BABYLON = {}));
  70364. //# sourceMappingURL=babylon.touchCamera.js.map
  70365. var BABYLON;
  70366. (function (BABYLON) {
  70367. var ProceduralTexture = /** @class */ (function (_super) {
  70368. __extends(ProceduralTexture, _super);
  70369. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70370. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70371. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70372. if (isCube === void 0) { isCube = false; }
  70373. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70374. _this.isCube = isCube;
  70375. _this.isEnabled = true;
  70376. _this._currentRefreshId = -1;
  70377. _this._refreshRate = 1;
  70378. _this._vertexBuffers = {};
  70379. _this._uniforms = new Array();
  70380. _this._samplers = new Array();
  70381. _this._textures = {};
  70382. _this._floats = {};
  70383. _this._floatsArrays = {};
  70384. _this._colors3 = {};
  70385. _this._colors4 = {};
  70386. _this._vectors2 = {};
  70387. _this._vectors3 = {};
  70388. _this._matrices = {};
  70389. _this._fallbackTextureUsed = false;
  70390. scene.proceduralTextures.push(_this);
  70391. _this._engine = scene.getEngine();
  70392. _this.name = name;
  70393. _this.isRenderTarget = true;
  70394. _this._size = size;
  70395. _this._generateMipMaps = generateMipMaps;
  70396. _this.setFragment(fragment);
  70397. _this._fallbackTexture = fallbackTexture;
  70398. if (isCube) {
  70399. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70400. _this.setFloat("face", 0);
  70401. }
  70402. else {
  70403. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70404. }
  70405. // VBO
  70406. var vertices = [];
  70407. vertices.push(1, 1);
  70408. vertices.push(-1, 1);
  70409. vertices.push(-1, -1);
  70410. vertices.push(1, -1);
  70411. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70412. _this._createIndexBuffer();
  70413. return _this;
  70414. }
  70415. ProceduralTexture.prototype._createIndexBuffer = function () {
  70416. var engine = this._engine;
  70417. // Indices
  70418. var indices = [];
  70419. indices.push(0);
  70420. indices.push(1);
  70421. indices.push(2);
  70422. indices.push(0);
  70423. indices.push(2);
  70424. indices.push(3);
  70425. this._indexBuffer = engine.createIndexBuffer(indices);
  70426. };
  70427. ProceduralTexture.prototype._rebuild = function () {
  70428. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70429. if (vb) {
  70430. vb._rebuild();
  70431. }
  70432. this._createIndexBuffer();
  70433. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70434. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70435. }
  70436. };
  70437. ProceduralTexture.prototype.reset = function () {
  70438. if (this._effect === undefined) {
  70439. return;
  70440. }
  70441. var engine = this._engine;
  70442. engine._releaseEffect(this._effect);
  70443. };
  70444. ProceduralTexture.prototype.isReady = function () {
  70445. var _this = this;
  70446. var engine = this._engine;
  70447. var shaders;
  70448. if (!this._fragment) {
  70449. return false;
  70450. }
  70451. if (this._fallbackTextureUsed) {
  70452. return true;
  70453. }
  70454. if (this._fragment.fragmentElement !== undefined) {
  70455. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70456. }
  70457. else {
  70458. shaders = { vertex: "procedural", fragment: this._fragment };
  70459. }
  70460. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70461. _this.releaseInternalTexture();
  70462. if (_this._fallbackTexture) {
  70463. _this._texture = _this._fallbackTexture._texture;
  70464. if (_this._texture) {
  70465. _this._texture.incrementReferences();
  70466. }
  70467. }
  70468. _this._fallbackTextureUsed = true;
  70469. });
  70470. return this._effect.isReady();
  70471. };
  70472. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70473. this._currentRefreshId = -1;
  70474. };
  70475. ProceduralTexture.prototype.setFragment = function (fragment) {
  70476. this._fragment = fragment;
  70477. };
  70478. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70479. get: function () {
  70480. return this._refreshRate;
  70481. },
  70482. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70483. set: function (value) {
  70484. this._refreshRate = value;
  70485. this.resetRefreshCounter();
  70486. },
  70487. enumerable: true,
  70488. configurable: true
  70489. });
  70490. ProceduralTexture.prototype._shouldRender = function () {
  70491. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70492. return false;
  70493. }
  70494. if (this._fallbackTextureUsed) {
  70495. return false;
  70496. }
  70497. if (this._currentRefreshId === -1) { // At least render once
  70498. this._currentRefreshId = 1;
  70499. return true;
  70500. }
  70501. if (this.refreshRate === this._currentRefreshId) {
  70502. this._currentRefreshId = 1;
  70503. return true;
  70504. }
  70505. this._currentRefreshId++;
  70506. return false;
  70507. };
  70508. ProceduralTexture.prototype.getRenderSize = function () {
  70509. return this._size;
  70510. };
  70511. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70512. if (this._fallbackTextureUsed) {
  70513. return;
  70514. }
  70515. this.releaseInternalTexture();
  70516. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70517. // Update properties
  70518. this._size = size;
  70519. this._generateMipMaps = generateMipMaps;
  70520. };
  70521. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70522. if (this._uniforms.indexOf(uniformName) === -1) {
  70523. this._uniforms.push(uniformName);
  70524. }
  70525. };
  70526. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70527. if (this._samplers.indexOf(name) === -1) {
  70528. this._samplers.push(name);
  70529. }
  70530. this._textures[name] = texture;
  70531. return this;
  70532. };
  70533. ProceduralTexture.prototype.setFloat = function (name, value) {
  70534. this._checkUniform(name);
  70535. this._floats[name] = value;
  70536. return this;
  70537. };
  70538. ProceduralTexture.prototype.setFloats = function (name, value) {
  70539. this._checkUniform(name);
  70540. this._floatsArrays[name] = value;
  70541. return this;
  70542. };
  70543. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70544. this._checkUniform(name);
  70545. this._colors3[name] = value;
  70546. return this;
  70547. };
  70548. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70549. this._checkUniform(name);
  70550. this._colors4[name] = value;
  70551. return this;
  70552. };
  70553. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70554. this._checkUniform(name);
  70555. this._vectors2[name] = value;
  70556. return this;
  70557. };
  70558. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70559. this._checkUniform(name);
  70560. this._vectors3[name] = value;
  70561. return this;
  70562. };
  70563. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70564. this._checkUniform(name);
  70565. this._matrices[name] = value;
  70566. return this;
  70567. };
  70568. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70569. var scene = this.getScene();
  70570. if (!scene) {
  70571. return;
  70572. }
  70573. var engine = this._engine;
  70574. // Render
  70575. engine.enableEffect(this._effect);
  70576. engine.setState(false);
  70577. // Texture
  70578. for (var name in this._textures) {
  70579. this._effect.setTexture(name, this._textures[name]);
  70580. }
  70581. // Float
  70582. for (name in this._floats) {
  70583. this._effect.setFloat(name, this._floats[name]);
  70584. }
  70585. // Floats
  70586. for (name in this._floatsArrays) {
  70587. this._effect.setArray(name, this._floatsArrays[name]);
  70588. }
  70589. // Color3
  70590. for (name in this._colors3) {
  70591. this._effect.setColor3(name, this._colors3[name]);
  70592. }
  70593. // Color4
  70594. for (name in this._colors4) {
  70595. var color = this._colors4[name];
  70596. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70597. }
  70598. // Vector2
  70599. for (name in this._vectors2) {
  70600. this._effect.setVector2(name, this._vectors2[name]);
  70601. }
  70602. // Vector3
  70603. for (name in this._vectors3) {
  70604. this._effect.setVector3(name, this._vectors3[name]);
  70605. }
  70606. // Matrix
  70607. for (name in this._matrices) {
  70608. this._effect.setMatrix(name, this._matrices[name]);
  70609. }
  70610. if (!this._texture) {
  70611. return;
  70612. }
  70613. if (this.isCube) {
  70614. for (var face = 0; face < 6; face++) {
  70615. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70616. // VBOs
  70617. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70618. this._effect.setFloat("face", face);
  70619. // Clear
  70620. engine.clear(scene.clearColor, true, true, true);
  70621. // Draw order
  70622. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70623. // Mipmaps
  70624. if (face === 5) {
  70625. engine.generateMipMapsForCubemap(this._texture);
  70626. }
  70627. }
  70628. }
  70629. else {
  70630. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70631. // VBOs
  70632. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70633. // Clear
  70634. engine.clear(scene.clearColor, true, true, true);
  70635. // Draw order
  70636. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70637. }
  70638. // Unbind
  70639. engine.unBindFramebuffer(this._texture, this.isCube);
  70640. if (this.onGenerated) {
  70641. this.onGenerated();
  70642. }
  70643. };
  70644. ProceduralTexture.prototype.clone = function () {
  70645. var textureSize = this.getSize();
  70646. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70647. // Base texture
  70648. newTexture.hasAlpha = this.hasAlpha;
  70649. newTexture.level = this.level;
  70650. // RenderTarget Texture
  70651. newTexture.coordinatesMode = this.coordinatesMode;
  70652. return newTexture;
  70653. };
  70654. ProceduralTexture.prototype.dispose = function () {
  70655. var scene = this.getScene();
  70656. if (!scene) {
  70657. return;
  70658. }
  70659. var index = scene.proceduralTextures.indexOf(this);
  70660. if (index >= 0) {
  70661. scene.proceduralTextures.splice(index, 1);
  70662. }
  70663. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70664. if (vertexBuffer) {
  70665. vertexBuffer.dispose();
  70666. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70667. }
  70668. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70669. this._indexBuffer = null;
  70670. }
  70671. _super.prototype.dispose.call(this);
  70672. };
  70673. __decorate([
  70674. BABYLON.serialize()
  70675. ], ProceduralTexture.prototype, "_size", void 0);
  70676. __decorate([
  70677. BABYLON.serialize()
  70678. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  70679. __decorate([
  70680. BABYLON.serialize()
  70681. ], ProceduralTexture.prototype, "isEnabled", void 0);
  70682. __decorate([
  70683. BABYLON.serialize()
  70684. ], ProceduralTexture.prototype, "refreshRate", null);
  70685. return ProceduralTexture;
  70686. }(BABYLON.Texture));
  70687. BABYLON.ProceduralTexture = ProceduralTexture;
  70688. })(BABYLON || (BABYLON = {}));
  70689. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70690. var BABYLON;
  70691. (function (BABYLON) {
  70692. var CustomProceduralTexture = /** @class */ (function (_super) {
  70693. __extends(CustomProceduralTexture, _super);
  70694. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70695. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70696. _this._animate = true;
  70697. _this._time = 0;
  70698. _this._texturePath = texturePath;
  70699. //Try to load json
  70700. _this.loadJson(texturePath);
  70701. _this.refreshRate = 1;
  70702. return _this;
  70703. }
  70704. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70705. var _this = this;
  70706. var noConfigFile = function () {
  70707. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70708. try {
  70709. _this.setFragment(_this._texturePath);
  70710. }
  70711. catch (ex) {
  70712. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70713. }
  70714. };
  70715. var configFileUrl = jsonUrl + "/config.json";
  70716. var xhr = new XMLHttpRequest();
  70717. xhr.open("GET", configFileUrl, true);
  70718. xhr.addEventListener("load", function () {
  70719. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70720. try {
  70721. _this._config = JSON.parse(xhr.response);
  70722. _this.updateShaderUniforms();
  70723. _this.updateTextures();
  70724. _this.setFragment(_this._texturePath + "/custom");
  70725. _this._animate = _this._config.animate;
  70726. _this.refreshRate = _this._config.refreshrate;
  70727. }
  70728. catch (ex) {
  70729. noConfigFile();
  70730. }
  70731. }
  70732. else {
  70733. noConfigFile();
  70734. }
  70735. }, false);
  70736. xhr.addEventListener("error", function () {
  70737. noConfigFile();
  70738. }, false);
  70739. try {
  70740. xhr.send();
  70741. }
  70742. catch (ex) {
  70743. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70744. }
  70745. };
  70746. CustomProceduralTexture.prototype.isReady = function () {
  70747. if (!_super.prototype.isReady.call(this)) {
  70748. return false;
  70749. }
  70750. for (var name in this._textures) {
  70751. var texture = this._textures[name];
  70752. if (!texture.isReady()) {
  70753. return false;
  70754. }
  70755. }
  70756. return true;
  70757. };
  70758. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70759. var scene = this.getScene();
  70760. if (this._animate && scene) {
  70761. this._time += scene.getAnimationRatio() * 0.03;
  70762. this.updateShaderUniforms();
  70763. }
  70764. _super.prototype.render.call(this, useCameraPostProcess);
  70765. };
  70766. CustomProceduralTexture.prototype.updateTextures = function () {
  70767. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70768. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70769. }
  70770. };
  70771. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70772. if (this._config) {
  70773. for (var j = 0; j < this._config.uniforms.length; j++) {
  70774. var uniform = this._config.uniforms[j];
  70775. switch (uniform.type) {
  70776. case "float":
  70777. this.setFloat(uniform.name, uniform.value);
  70778. break;
  70779. case "color3":
  70780. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70781. break;
  70782. case "color4":
  70783. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70784. break;
  70785. case "vector2":
  70786. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70787. break;
  70788. case "vector3":
  70789. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70790. break;
  70791. }
  70792. }
  70793. }
  70794. this.setFloat("time", this._time);
  70795. };
  70796. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70797. get: function () {
  70798. return this._animate;
  70799. },
  70800. set: function (value) {
  70801. this._animate = value;
  70802. },
  70803. enumerable: true,
  70804. configurable: true
  70805. });
  70806. return CustomProceduralTexture;
  70807. }(BABYLON.ProceduralTexture));
  70808. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70809. })(BABYLON || (BABYLON = {}));
  70810. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70811. var BABYLON;
  70812. (function (BABYLON) {
  70813. var FreeCameraGamepadInput = /** @class */ (function () {
  70814. function FreeCameraGamepadInput() {
  70815. this.gamepadAngularSensibility = 200;
  70816. this.gamepadMoveSensibility = 40;
  70817. // private members
  70818. this._cameraTransform = BABYLON.Matrix.Identity();
  70819. this._deltaTransform = BABYLON.Vector3.Zero();
  70820. this._vector3 = BABYLON.Vector3.Zero();
  70821. this._vector2 = BABYLON.Vector2.Zero();
  70822. }
  70823. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70824. var _this = this;
  70825. var manager = this.camera.getScene().gamepadManager;
  70826. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70827. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70828. // prioritize XBOX gamepads.
  70829. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70830. _this.gamepad = gamepad;
  70831. }
  70832. }
  70833. });
  70834. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70835. if (_this.gamepad === gamepad) {
  70836. _this.gamepad = null;
  70837. }
  70838. });
  70839. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70840. };
  70841. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70842. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70843. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70844. this.gamepad = null;
  70845. };
  70846. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70847. if (this.gamepad && this.gamepad.leftStick) {
  70848. var camera = this.camera;
  70849. var LSValues = this.gamepad.leftStick;
  70850. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70851. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70852. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70853. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70854. var RSValues = this.gamepad.rightStick;
  70855. if (RSValues) {
  70856. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70857. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70858. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70859. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70860. }
  70861. else {
  70862. RSValues = { x: 0, y: 0 };
  70863. }
  70864. if (!camera.rotationQuaternion) {
  70865. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70866. }
  70867. else {
  70868. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70869. }
  70870. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70871. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70872. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70873. camera.cameraDirection.addInPlace(this._deltaTransform);
  70874. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70875. camera.cameraRotation.addInPlace(this._vector2);
  70876. }
  70877. };
  70878. FreeCameraGamepadInput.prototype.getClassName = function () {
  70879. return "FreeCameraGamepadInput";
  70880. };
  70881. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70882. return "gamepad";
  70883. };
  70884. __decorate([
  70885. BABYLON.serialize()
  70886. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70887. __decorate([
  70888. BABYLON.serialize()
  70889. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70890. return FreeCameraGamepadInput;
  70891. }());
  70892. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70893. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70894. })(BABYLON || (BABYLON = {}));
  70895. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70896. var BABYLON;
  70897. (function (BABYLON) {
  70898. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70899. function ArcRotateCameraGamepadInput() {
  70900. this.gamepadRotationSensibility = 80;
  70901. this.gamepadMoveSensibility = 40;
  70902. }
  70903. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70904. var _this = this;
  70905. var manager = this.camera.getScene().gamepadManager;
  70906. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70907. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70908. // prioritize XBOX gamepads.
  70909. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70910. _this.gamepad = gamepad;
  70911. }
  70912. }
  70913. });
  70914. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70915. if (_this.gamepad === gamepad) {
  70916. _this.gamepad = null;
  70917. }
  70918. });
  70919. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70920. };
  70921. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70922. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70923. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70924. this.gamepad = null;
  70925. };
  70926. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70927. if (this.gamepad) {
  70928. var camera = this.camera;
  70929. var RSValues = this.gamepad.rightStick;
  70930. if (RSValues) {
  70931. if (RSValues.x != 0) {
  70932. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70933. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70934. camera.inertialAlphaOffset += normalizedRX;
  70935. }
  70936. }
  70937. if (RSValues.y != 0) {
  70938. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70939. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70940. camera.inertialBetaOffset += normalizedRY;
  70941. }
  70942. }
  70943. }
  70944. var LSValues = this.gamepad.leftStick;
  70945. if (LSValues && LSValues.y != 0) {
  70946. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70947. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70948. this.camera.inertialRadiusOffset -= normalizedLY;
  70949. }
  70950. }
  70951. }
  70952. };
  70953. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70954. return "ArcRotateCameraGamepadInput";
  70955. };
  70956. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70957. return "gamepad";
  70958. };
  70959. __decorate([
  70960. BABYLON.serialize()
  70961. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70962. __decorate([
  70963. BABYLON.serialize()
  70964. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70965. return ArcRotateCameraGamepadInput;
  70966. }());
  70967. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70968. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70969. })(BABYLON || (BABYLON = {}));
  70970. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70971. var BABYLON;
  70972. (function (BABYLON) {
  70973. var GamepadManager = /** @class */ (function () {
  70974. function GamepadManager(_scene) {
  70975. var _this = this;
  70976. this._scene = _scene;
  70977. this._babylonGamepads = [];
  70978. this._oneGamepadConnected = false;
  70979. this._isMonitoring = false;
  70980. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70981. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70982. this._gamepadEventSupported = false;
  70983. }
  70984. else {
  70985. this._gamepadEventSupported = 'GamepadEvent' in window;
  70986. this._gamepadSupport = (navigator.getGamepads ||
  70987. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70988. }
  70989. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70990. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70991. for (var i in _this._babylonGamepads) {
  70992. var gamepad = _this._babylonGamepads[i];
  70993. if (gamepad && gamepad._isConnected) {
  70994. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70995. }
  70996. }
  70997. });
  70998. this._onGamepadConnectedEvent = function (evt) {
  70999. var gamepad = evt.gamepad;
  71000. if (gamepad.index in _this._babylonGamepads) {
  71001. if (_this._babylonGamepads[gamepad.index].isConnected) {
  71002. return;
  71003. }
  71004. }
  71005. var newGamepad;
  71006. if (_this._babylonGamepads[gamepad.index]) {
  71007. newGamepad = _this._babylonGamepads[gamepad.index];
  71008. newGamepad.browserGamepad = gamepad;
  71009. newGamepad._isConnected = true;
  71010. }
  71011. else {
  71012. newGamepad = _this._addNewGamepad(gamepad);
  71013. }
  71014. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71015. _this._startMonitoringGamepads();
  71016. };
  71017. this._onGamepadDisconnectedEvent = function (evt) {
  71018. var gamepad = evt.gamepad;
  71019. // Remove the gamepad from the list of gamepads to monitor.
  71020. for (var i in _this._babylonGamepads) {
  71021. if (_this._babylonGamepads[i].index === gamepad.index) {
  71022. var disconnectedGamepad = _this._babylonGamepads[i];
  71023. disconnectedGamepad._isConnected = false;
  71024. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  71025. break;
  71026. }
  71027. }
  71028. };
  71029. if (this._gamepadSupport) {
  71030. //first add already-connected gamepads
  71031. this._updateGamepadObjects();
  71032. if (this._babylonGamepads.length) {
  71033. this._startMonitoringGamepads();
  71034. }
  71035. // Checking if the gamepad connected event is supported (like in Firefox)
  71036. if (this._gamepadEventSupported) {
  71037. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  71038. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  71039. }
  71040. else {
  71041. this._startMonitoringGamepads();
  71042. }
  71043. }
  71044. }
  71045. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  71046. get: function () {
  71047. return this._babylonGamepads;
  71048. },
  71049. enumerable: true,
  71050. configurable: true
  71051. });
  71052. GamepadManager.prototype.getGamepadByType = function (type) {
  71053. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  71054. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  71055. var gamepad = _a[_i];
  71056. if (gamepad && gamepad.type === type) {
  71057. return gamepad;
  71058. }
  71059. }
  71060. return null;
  71061. };
  71062. GamepadManager.prototype.dispose = function () {
  71063. if (this._gamepadEventSupported) {
  71064. if (this._onGamepadConnectedEvent) {
  71065. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  71066. }
  71067. if (this._onGamepadDisconnectedEvent) {
  71068. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  71069. }
  71070. this._onGamepadConnectedEvent = null;
  71071. this._onGamepadDisconnectedEvent = null;
  71072. }
  71073. this._babylonGamepads.forEach(function (gamepad) {
  71074. gamepad.dispose();
  71075. });
  71076. this.onGamepadConnectedObservable.clear();
  71077. this.onGamepadDisconnectedObservable.clear();
  71078. this._oneGamepadConnected = false;
  71079. this._stopMonitoringGamepads();
  71080. this._babylonGamepads = [];
  71081. };
  71082. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  71083. if (!this._oneGamepadConnected) {
  71084. this._oneGamepadConnected = true;
  71085. }
  71086. var newGamepad;
  71087. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  71088. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  71089. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  71090. }
  71091. // if pose is supported, use the (WebVR) pose enabled controller
  71092. else if (gamepad.pose) {
  71093. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  71094. }
  71095. else {
  71096. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  71097. }
  71098. this._babylonGamepads[newGamepad.index] = newGamepad;
  71099. return newGamepad;
  71100. };
  71101. GamepadManager.prototype._startMonitoringGamepads = function () {
  71102. if (!this._isMonitoring) {
  71103. this._isMonitoring = true;
  71104. //back-comp
  71105. if (!this._scene) {
  71106. this._checkGamepadsStatus();
  71107. }
  71108. }
  71109. };
  71110. GamepadManager.prototype._stopMonitoringGamepads = function () {
  71111. this._isMonitoring = false;
  71112. };
  71113. GamepadManager.prototype._checkGamepadsStatus = function () {
  71114. var _this = this;
  71115. // Hack to be compatible Chrome
  71116. this._updateGamepadObjects();
  71117. for (var i in this._babylonGamepads) {
  71118. var gamepad = this._babylonGamepads[i];
  71119. if (!gamepad || !gamepad.isConnected) {
  71120. continue;
  71121. }
  71122. gamepad.update();
  71123. }
  71124. if (this._isMonitoring && !this._scene) {
  71125. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  71126. }
  71127. };
  71128. // This function is called only on Chrome, which does not properly support
  71129. // connection/disconnection events and forces you to recopy again the gamepad object
  71130. GamepadManager.prototype._updateGamepadObjects = function () {
  71131. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  71132. for (var i = 0; i < gamepads.length; i++) {
  71133. var gamepad = gamepads[i];
  71134. if (gamepad) {
  71135. if (!this._babylonGamepads[gamepad.index]) {
  71136. var newGamepad = this._addNewGamepad(gamepad);
  71137. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71138. }
  71139. else {
  71140. // Forced to copy again this object for Chrome for unknown reason
  71141. this._babylonGamepads[i].browserGamepad = gamepad;
  71142. if (!this._babylonGamepads[i].isConnected) {
  71143. this._babylonGamepads[i]._isConnected = true;
  71144. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  71145. }
  71146. }
  71147. }
  71148. }
  71149. };
  71150. return GamepadManager;
  71151. }());
  71152. BABYLON.GamepadManager = GamepadManager;
  71153. })(BABYLON || (BABYLON = {}));
  71154. //# sourceMappingURL=babylon.gamepadManager.js.map
  71155. var BABYLON;
  71156. (function (BABYLON) {
  71157. var StickValues = /** @class */ (function () {
  71158. function StickValues(x, y) {
  71159. this.x = x;
  71160. this.y = y;
  71161. }
  71162. return StickValues;
  71163. }());
  71164. BABYLON.StickValues = StickValues;
  71165. var Gamepad = /** @class */ (function () {
  71166. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  71167. if (leftStickX === void 0) { leftStickX = 0; }
  71168. if (leftStickY === void 0) { leftStickY = 1; }
  71169. if (rightStickX === void 0) { rightStickX = 2; }
  71170. if (rightStickY === void 0) { rightStickY = 3; }
  71171. this.id = id;
  71172. this.index = index;
  71173. this.browserGamepad = browserGamepad;
  71174. this._isConnected = true;
  71175. this._invertLeftStickY = false;
  71176. this.type = Gamepad.GAMEPAD;
  71177. this._leftStickAxisX = leftStickX;
  71178. this._leftStickAxisY = leftStickY;
  71179. this._rightStickAxisX = rightStickX;
  71180. this._rightStickAxisY = rightStickY;
  71181. if (this.browserGamepad.axes.length >= 2) {
  71182. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71183. }
  71184. if (this.browserGamepad.axes.length >= 4) {
  71185. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71186. }
  71187. }
  71188. Object.defineProperty(Gamepad.prototype, "isConnected", {
  71189. get: function () {
  71190. return this._isConnected;
  71191. },
  71192. enumerable: true,
  71193. configurable: true
  71194. });
  71195. Gamepad.prototype.onleftstickchanged = function (callback) {
  71196. this._onleftstickchanged = callback;
  71197. };
  71198. Gamepad.prototype.onrightstickchanged = function (callback) {
  71199. this._onrightstickchanged = callback;
  71200. };
  71201. Object.defineProperty(Gamepad.prototype, "leftStick", {
  71202. get: function () {
  71203. return this._leftStick;
  71204. },
  71205. set: function (newValues) {
  71206. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  71207. this._onleftstickchanged(newValues);
  71208. }
  71209. this._leftStick = newValues;
  71210. },
  71211. enumerable: true,
  71212. configurable: true
  71213. });
  71214. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71215. get: function () {
  71216. return this._rightStick;
  71217. },
  71218. set: function (newValues) {
  71219. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71220. this._onrightstickchanged(newValues);
  71221. }
  71222. this._rightStick = newValues;
  71223. },
  71224. enumerable: true,
  71225. configurable: true
  71226. });
  71227. Gamepad.prototype.update = function () {
  71228. if (this._leftStick) {
  71229. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71230. if (this._invertLeftStickY) {
  71231. this.leftStick.y *= -1;
  71232. }
  71233. }
  71234. if (this._rightStick) {
  71235. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71236. }
  71237. };
  71238. Gamepad.prototype.dispose = function () {
  71239. };
  71240. Gamepad.GAMEPAD = 0;
  71241. Gamepad.GENERIC = 1;
  71242. Gamepad.XBOX = 2;
  71243. Gamepad.POSE_ENABLED = 3;
  71244. return Gamepad;
  71245. }());
  71246. BABYLON.Gamepad = Gamepad;
  71247. var GenericPad = /** @class */ (function (_super) {
  71248. __extends(GenericPad, _super);
  71249. function GenericPad(id, index, browserGamepad) {
  71250. var _this = _super.call(this, id, index, browserGamepad) || this;
  71251. _this.onButtonDownObservable = new BABYLON.Observable();
  71252. _this.onButtonUpObservable = new BABYLON.Observable();
  71253. _this.type = Gamepad.GENERIC;
  71254. _this._buttons = new Array(browserGamepad.buttons.length);
  71255. return _this;
  71256. }
  71257. GenericPad.prototype.onbuttondown = function (callback) {
  71258. this._onbuttondown = callback;
  71259. };
  71260. GenericPad.prototype.onbuttonup = function (callback) {
  71261. this._onbuttonup = callback;
  71262. };
  71263. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71264. if (newValue !== currentValue) {
  71265. if (newValue === 1) {
  71266. if (this._onbuttondown) {
  71267. this._onbuttondown(buttonIndex);
  71268. }
  71269. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71270. }
  71271. if (newValue === 0) {
  71272. if (this._onbuttonup) {
  71273. this._onbuttonup(buttonIndex);
  71274. }
  71275. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71276. }
  71277. }
  71278. return newValue;
  71279. };
  71280. GenericPad.prototype.update = function () {
  71281. _super.prototype.update.call(this);
  71282. for (var index = 0; index < this._buttons.length; index++) {
  71283. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71284. }
  71285. };
  71286. GenericPad.prototype.dispose = function () {
  71287. _super.prototype.dispose.call(this);
  71288. this.onButtonDownObservable.clear();
  71289. this.onButtonUpObservable.clear();
  71290. };
  71291. return GenericPad;
  71292. }(Gamepad));
  71293. BABYLON.GenericPad = GenericPad;
  71294. })(BABYLON || (BABYLON = {}));
  71295. //# sourceMappingURL=babylon.gamepad.js.map
  71296. var BABYLON;
  71297. (function (BABYLON) {
  71298. /**
  71299. * Defines supported buttons for XBox360 compatible gamepads
  71300. */
  71301. var Xbox360Button;
  71302. (function (Xbox360Button) {
  71303. /** A */
  71304. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71305. /** B */
  71306. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71307. /** X */
  71308. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71309. /** Y */
  71310. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71311. /** Start */
  71312. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71313. /** Back */
  71314. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71315. /** Left button */
  71316. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71317. /** Right button */
  71318. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71319. /** Left stick */
  71320. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71321. /** Right stick */
  71322. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71323. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71324. /** Defines values for XBox360 DPad */
  71325. var Xbox360Dpad;
  71326. (function (Xbox360Dpad) {
  71327. /** Up */
  71328. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71329. /** Down */
  71330. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71331. /** Left */
  71332. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71333. /** Right */
  71334. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71335. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71336. /**
  71337. * Defines a XBox360 gamepad
  71338. */
  71339. var Xbox360Pad = /** @class */ (function (_super) {
  71340. __extends(Xbox360Pad, _super);
  71341. /**
  71342. * Creates a new XBox360 gamepad object
  71343. * @param id defines the id of this gamepad
  71344. * @param index defines its index
  71345. * @param gamepad defines the internal HTML gamepad object
  71346. * @param xboxOne defines if it is a XBox One gamepad
  71347. */
  71348. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71349. if (xboxOne === void 0) { xboxOne = false; }
  71350. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71351. _this._leftTrigger = 0;
  71352. _this._rightTrigger = 0;
  71353. /** Observable raised when a button is pressed */
  71354. _this.onButtonDownObservable = new BABYLON.Observable();
  71355. /** Observable raised when a button is released */
  71356. _this.onButtonUpObservable = new BABYLON.Observable();
  71357. /** Observable raised when a pad is pressed */
  71358. _this.onPadDownObservable = new BABYLON.Observable();
  71359. /** Observable raised when a pad is released */
  71360. _this.onPadUpObservable = new BABYLON.Observable();
  71361. _this._buttonA = 0;
  71362. _this._buttonB = 0;
  71363. _this._buttonX = 0;
  71364. _this._buttonY = 0;
  71365. _this._buttonBack = 0;
  71366. _this._buttonStart = 0;
  71367. _this._buttonLB = 0;
  71368. _this._buttonRB = 0;
  71369. _this._buttonLeftStick = 0;
  71370. _this._buttonRightStick = 0;
  71371. _this._dPadUp = 0;
  71372. _this._dPadDown = 0;
  71373. _this._dPadLeft = 0;
  71374. _this._dPadRight = 0;
  71375. _this._isXboxOnePad = false;
  71376. _this.type = BABYLON.Gamepad.XBOX;
  71377. _this._isXboxOnePad = xboxOne;
  71378. return _this;
  71379. }
  71380. /**
  71381. * Defines the callback to call when left trigger is pressed
  71382. * @param callback defines the callback to use
  71383. */
  71384. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71385. this._onlefttriggerchanged = callback;
  71386. };
  71387. /**
  71388. * Defines the callback to call when right trigger is pressed
  71389. * @param callback defines the callback to use
  71390. */
  71391. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71392. this._onrighttriggerchanged = callback;
  71393. };
  71394. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71395. /**
  71396. * Gets or sets left trigger value
  71397. */
  71398. get: function () {
  71399. return this._leftTrigger;
  71400. },
  71401. set: function (newValue) {
  71402. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71403. this._onlefttriggerchanged(newValue);
  71404. }
  71405. this._leftTrigger = newValue;
  71406. },
  71407. enumerable: true,
  71408. configurable: true
  71409. });
  71410. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71411. /**
  71412. * Gets or sets right trigger value
  71413. */
  71414. get: function () {
  71415. return this._rightTrigger;
  71416. },
  71417. set: function (newValue) {
  71418. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71419. this._onrighttriggerchanged(newValue);
  71420. }
  71421. this._rightTrigger = newValue;
  71422. },
  71423. enumerable: true,
  71424. configurable: true
  71425. });
  71426. /**
  71427. * Defines the callback to call when a button is pressed
  71428. * @param callback defines the callback to use
  71429. */
  71430. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71431. this._onbuttondown = callback;
  71432. };
  71433. /**
  71434. * Defines the callback to call when a button is released
  71435. * @param callback defines the callback to use
  71436. */
  71437. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71438. this._onbuttonup = callback;
  71439. };
  71440. /**
  71441. * Defines the callback to call when a pad is pressed
  71442. * @param callback defines the callback to use
  71443. */
  71444. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71445. this._ondpaddown = callback;
  71446. };
  71447. /**
  71448. * Defines the callback to call when a pad is released
  71449. * @param callback defines the callback to use
  71450. */
  71451. Xbox360Pad.prototype.ondpadup = function (callback) {
  71452. this._ondpadup = callback;
  71453. };
  71454. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71455. if (newValue !== currentValue) {
  71456. if (newValue === 1) {
  71457. if (this._onbuttondown) {
  71458. this._onbuttondown(buttonType);
  71459. }
  71460. this.onButtonDownObservable.notifyObservers(buttonType);
  71461. }
  71462. if (newValue === 0) {
  71463. if (this._onbuttonup) {
  71464. this._onbuttonup(buttonType);
  71465. }
  71466. this.onButtonUpObservable.notifyObservers(buttonType);
  71467. }
  71468. }
  71469. return newValue;
  71470. };
  71471. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71472. if (newValue !== currentValue) {
  71473. if (newValue === 1) {
  71474. if (this._ondpaddown) {
  71475. this._ondpaddown(buttonType);
  71476. }
  71477. this.onPadDownObservable.notifyObservers(buttonType);
  71478. }
  71479. if (newValue === 0) {
  71480. if (this._ondpadup) {
  71481. this._ondpadup(buttonType);
  71482. }
  71483. this.onPadUpObservable.notifyObservers(buttonType);
  71484. }
  71485. }
  71486. return newValue;
  71487. };
  71488. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71489. /** Gets or sets value of A button */
  71490. get: function () {
  71491. return this._buttonA;
  71492. },
  71493. set: function (value) {
  71494. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71495. },
  71496. enumerable: true,
  71497. configurable: true
  71498. });
  71499. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71500. /** Gets or sets value of B button */
  71501. get: function () {
  71502. return this._buttonB;
  71503. },
  71504. set: function (value) {
  71505. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71506. },
  71507. enumerable: true,
  71508. configurable: true
  71509. });
  71510. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71511. /** Gets or sets value of X button */
  71512. get: function () {
  71513. return this._buttonX;
  71514. },
  71515. set: function (value) {
  71516. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71517. },
  71518. enumerable: true,
  71519. configurable: true
  71520. });
  71521. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71522. /** Gets or sets value of Y button */
  71523. get: function () {
  71524. return this._buttonY;
  71525. },
  71526. set: function (value) {
  71527. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71528. },
  71529. enumerable: true,
  71530. configurable: true
  71531. });
  71532. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71533. /** Gets or sets value of Start button */
  71534. get: function () {
  71535. return this._buttonStart;
  71536. },
  71537. set: function (value) {
  71538. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71539. },
  71540. enumerable: true,
  71541. configurable: true
  71542. });
  71543. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71544. /** Gets or sets value of Back button */
  71545. get: function () {
  71546. return this._buttonBack;
  71547. },
  71548. set: function (value) {
  71549. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71550. },
  71551. enumerable: true,
  71552. configurable: true
  71553. });
  71554. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71555. /** Gets or sets value of Left button */
  71556. get: function () {
  71557. return this._buttonLB;
  71558. },
  71559. set: function (value) {
  71560. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71561. },
  71562. enumerable: true,
  71563. configurable: true
  71564. });
  71565. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71566. /** Gets or sets value of Right button */
  71567. get: function () {
  71568. return this._buttonRB;
  71569. },
  71570. set: function (value) {
  71571. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71572. },
  71573. enumerable: true,
  71574. configurable: true
  71575. });
  71576. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71577. /** Gets or sets value of left stick */
  71578. get: function () {
  71579. return this._buttonLeftStick;
  71580. },
  71581. set: function (value) {
  71582. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71583. },
  71584. enumerable: true,
  71585. configurable: true
  71586. });
  71587. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71588. /** Gets or sets value of right stick */
  71589. get: function () {
  71590. return this._buttonRightStick;
  71591. },
  71592. set: function (value) {
  71593. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71594. },
  71595. enumerable: true,
  71596. configurable: true
  71597. });
  71598. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71599. /** Gets or sets value of DPad up */
  71600. get: function () {
  71601. return this._dPadUp;
  71602. },
  71603. set: function (value) {
  71604. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71605. },
  71606. enumerable: true,
  71607. configurable: true
  71608. });
  71609. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71610. /** Gets or sets value of DPad down */
  71611. get: function () {
  71612. return this._dPadDown;
  71613. },
  71614. set: function (value) {
  71615. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71616. },
  71617. enumerable: true,
  71618. configurable: true
  71619. });
  71620. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71621. /** Gets or sets value of DPad left */
  71622. get: function () {
  71623. return this._dPadLeft;
  71624. },
  71625. set: function (value) {
  71626. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71627. },
  71628. enumerable: true,
  71629. configurable: true
  71630. });
  71631. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71632. /** Gets or sets value of DPad right */
  71633. get: function () {
  71634. return this._dPadRight;
  71635. },
  71636. set: function (value) {
  71637. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71638. },
  71639. enumerable: true,
  71640. configurable: true
  71641. });
  71642. /**
  71643. * Force the gamepad to synchronize with device values
  71644. */
  71645. Xbox360Pad.prototype.update = function () {
  71646. _super.prototype.update.call(this);
  71647. if (this._isXboxOnePad) {
  71648. this.buttonA = this.browserGamepad.buttons[0].value;
  71649. this.buttonB = this.browserGamepad.buttons[1].value;
  71650. this.buttonX = this.browserGamepad.buttons[2].value;
  71651. this.buttonY = this.browserGamepad.buttons[3].value;
  71652. this.buttonLB = this.browserGamepad.buttons[4].value;
  71653. this.buttonRB = this.browserGamepad.buttons[5].value;
  71654. this.leftTrigger = this.browserGamepad.axes[2];
  71655. this.rightTrigger = this.browserGamepad.axes[5];
  71656. this.buttonBack = this.browserGamepad.buttons[9].value;
  71657. this.buttonStart = this.browserGamepad.buttons[8].value;
  71658. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71659. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71660. this.dPadUp = this.browserGamepad.buttons[11].value;
  71661. this.dPadDown = this.browserGamepad.buttons[12].value;
  71662. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71663. this.dPadRight = this.browserGamepad.buttons[14].value;
  71664. }
  71665. else {
  71666. this.buttonA = this.browserGamepad.buttons[0].value;
  71667. this.buttonB = this.browserGamepad.buttons[1].value;
  71668. this.buttonX = this.browserGamepad.buttons[2].value;
  71669. this.buttonY = this.browserGamepad.buttons[3].value;
  71670. this.buttonLB = this.browserGamepad.buttons[4].value;
  71671. this.buttonRB = this.browserGamepad.buttons[5].value;
  71672. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71673. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71674. this.buttonBack = this.browserGamepad.buttons[8].value;
  71675. this.buttonStart = this.browserGamepad.buttons[9].value;
  71676. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71677. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71678. this.dPadUp = this.browserGamepad.buttons[12].value;
  71679. this.dPadDown = this.browserGamepad.buttons[13].value;
  71680. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71681. this.dPadRight = this.browserGamepad.buttons[15].value;
  71682. }
  71683. };
  71684. Xbox360Pad.prototype.dispose = function () {
  71685. _super.prototype.dispose.call(this);
  71686. this.onButtonDownObservable.clear();
  71687. this.onButtonUpObservable.clear();
  71688. this.onPadDownObservable.clear();
  71689. this.onPadUpObservable.clear();
  71690. };
  71691. return Xbox360Pad;
  71692. }(BABYLON.Gamepad));
  71693. BABYLON.Xbox360Pad = Xbox360Pad;
  71694. })(BABYLON || (BABYLON = {}));
  71695. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71696. var BABYLON;
  71697. (function (BABYLON) {
  71698. /**
  71699. * Defines the types of pose enabled controllers that are supported
  71700. */
  71701. var PoseEnabledControllerType;
  71702. (function (PoseEnabledControllerType) {
  71703. /**
  71704. * HTC Vive
  71705. */
  71706. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71707. /**
  71708. * Oculus Rift
  71709. */
  71710. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71711. /**
  71712. * Windows mixed reality
  71713. */
  71714. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71715. /**
  71716. * Samsung gear VR
  71717. */
  71718. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71719. /**
  71720. * Google Daydream
  71721. */
  71722. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71723. /**
  71724. * Generic
  71725. */
  71726. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71727. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71728. /**
  71729. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71730. */
  71731. var PoseEnabledControllerHelper = /** @class */ (function () {
  71732. function PoseEnabledControllerHelper() {
  71733. }
  71734. /**
  71735. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71736. * @param vrGamepad the gamepad to initialized
  71737. * @returns a vr controller of the type the gamepad identified as
  71738. */
  71739. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71740. // Oculus Touch
  71741. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71742. return new BABYLON.OculusTouchController(vrGamepad);
  71743. }
  71744. // Windows Mixed Reality controllers
  71745. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71746. return new BABYLON.WindowsMotionController(vrGamepad);
  71747. }
  71748. // HTC Vive
  71749. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71750. return new BABYLON.ViveController(vrGamepad);
  71751. }
  71752. // Samsung/Oculus Gear VR or Oculus Go
  71753. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71754. return new BABYLON.GearVRController(vrGamepad);
  71755. }
  71756. // Google Daydream
  71757. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71758. return new BABYLON.DaydreamController(vrGamepad);
  71759. }
  71760. // Generic
  71761. else {
  71762. return new BABYLON.GenericController(vrGamepad);
  71763. }
  71764. };
  71765. return PoseEnabledControllerHelper;
  71766. }());
  71767. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71768. /**
  71769. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71770. */
  71771. var PoseEnabledController = /** @class */ (function (_super) {
  71772. __extends(PoseEnabledController, _super);
  71773. /**
  71774. * Creates a new PoseEnabledController from a gamepad
  71775. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71776. */
  71777. function PoseEnabledController(browserGamepad) {
  71778. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71779. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71780. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71781. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71782. /**
  71783. * The device position in babylon space
  71784. */
  71785. _this.devicePosition = BABYLON.Vector3.Zero();
  71786. /**
  71787. * The device rotation in babylon space
  71788. */
  71789. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71790. /**
  71791. * The scale factor of the device in babylon space
  71792. */
  71793. _this.deviceScaleFactor = 1;
  71794. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71795. /**
  71796. * Internal, matrix used to convert room space to babylon space
  71797. */
  71798. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71799. /**
  71800. * Node to be used when casting a ray from the controller
  71801. */
  71802. _this._pointingPoseNode = null;
  71803. _this._workingMatrix = BABYLON.Matrix.Identity();
  71804. /**
  71805. * @hidden
  71806. */
  71807. _this._meshAttachedObservable = new BABYLON.Observable();
  71808. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71809. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71810. _this.position = BABYLON.Vector3.Zero();
  71811. _this.rotationQuaternion = new BABYLON.Quaternion();
  71812. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71813. _this._calculatedRotation = new BABYLON.Quaternion();
  71814. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71815. return _this;
  71816. }
  71817. /**
  71818. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71819. */
  71820. PoseEnabledController.prototype.update = function () {
  71821. _super.prototype.update.call(this);
  71822. this._updatePoseAndMesh();
  71823. };
  71824. /**
  71825. * Updates only the pose device and mesh without doing any button event checking
  71826. */
  71827. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  71828. var pose = this.browserGamepad.pose;
  71829. this.updateFromDevice(pose);
  71830. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71831. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71832. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71833. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71834. if (this._mesh) {
  71835. this._mesh.position.copyFrom(this.devicePosition);
  71836. if (this._mesh.rotationQuaternion) {
  71837. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71838. }
  71839. }
  71840. };
  71841. /**
  71842. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71843. * @param poseData raw pose fromthe device
  71844. */
  71845. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71846. if (poseData) {
  71847. this.rawPose = poseData;
  71848. if (poseData.position) {
  71849. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71850. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71851. this._deviceRoomPosition.z *= -1;
  71852. }
  71853. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71854. this._calculatedPosition.addInPlace(this.position);
  71855. }
  71856. var pose = this.rawPose;
  71857. if (poseData.orientation && pose.orientation) {
  71858. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71859. if (this._mesh) {
  71860. if (this._mesh.getScene().useRightHandedSystem) {
  71861. this._deviceRoomRotationQuaternion.z *= -1;
  71862. this._deviceRoomRotationQuaternion.w *= -1;
  71863. }
  71864. else {
  71865. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71866. }
  71867. }
  71868. // if the camera is set, rotate to the camera's rotation
  71869. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71870. }
  71871. }
  71872. };
  71873. /**
  71874. * Attaches a mesh to the controller
  71875. * @param mesh the mesh to be attached
  71876. */
  71877. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71878. if (this._mesh) {
  71879. this._mesh.parent = null;
  71880. }
  71881. this._mesh = mesh;
  71882. if (this._poseControlledCamera) {
  71883. this._mesh.parent = this._poseControlledCamera;
  71884. }
  71885. if (!this._mesh.rotationQuaternion) {
  71886. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71887. }
  71888. // 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
  71889. this._updatePoseAndMesh();
  71890. if (this._pointingPoseNode) {
  71891. var parents = [];
  71892. var obj = this._pointingPoseNode;
  71893. while (obj.parent) {
  71894. parents.push(obj.parent);
  71895. obj = obj.parent;
  71896. }
  71897. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  71898. }
  71899. this._meshAttachedObservable.notifyObservers(mesh);
  71900. };
  71901. /**
  71902. * Attaches the controllers mesh to a camera
  71903. * @param camera the camera the mesh should be attached to
  71904. */
  71905. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71906. this._poseControlledCamera = camera;
  71907. if (this._mesh) {
  71908. this._mesh.parent = this._poseControlledCamera;
  71909. }
  71910. };
  71911. /**
  71912. * Disposes of the controller
  71913. */
  71914. PoseEnabledController.prototype.dispose = function () {
  71915. if (this._mesh) {
  71916. this._mesh.dispose();
  71917. }
  71918. this._mesh = null;
  71919. _super.prototype.dispose.call(this);
  71920. };
  71921. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71922. /**
  71923. * The mesh that is attached to the controller
  71924. */
  71925. get: function () {
  71926. return this._mesh;
  71927. },
  71928. enumerable: true,
  71929. configurable: true
  71930. });
  71931. /**
  71932. * Gets the ray of the controller in the direction the controller is pointing
  71933. * @param length the length the resulting ray should be
  71934. * @returns a ray in the direction the controller is pointing
  71935. */
  71936. PoseEnabledController.prototype.getForwardRay = function (length) {
  71937. if (length === void 0) { length = 100; }
  71938. if (!this.mesh) {
  71939. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71940. }
  71941. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71942. var origin = m.getTranslation();
  71943. var forward = new BABYLON.Vector3(0, 0, -1);
  71944. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71945. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71946. return new BABYLON.Ray(origin, direction, length);
  71947. };
  71948. /**
  71949. * Name of the child mesh that can be used to cast a ray from the controller
  71950. */
  71951. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71952. return PoseEnabledController;
  71953. }(BABYLON.Gamepad));
  71954. BABYLON.PoseEnabledController = PoseEnabledController;
  71955. })(BABYLON || (BABYLON = {}));
  71956. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71957. var BABYLON;
  71958. (function (BABYLON) {
  71959. /**
  71960. * Defines the WebVRController object that represents controllers tracked in 3D space
  71961. */
  71962. var WebVRController = /** @class */ (function (_super) {
  71963. __extends(WebVRController, _super);
  71964. /**
  71965. * Creates a new WebVRController from a gamepad
  71966. * @param vrGamepad the gamepad that the WebVRController should be created from
  71967. */
  71968. function WebVRController(vrGamepad) {
  71969. var _this = _super.call(this, vrGamepad) || this;
  71970. // Observables
  71971. /**
  71972. * Fired when the trigger state has changed
  71973. */
  71974. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71975. /**
  71976. * Fired when the main button state has changed
  71977. */
  71978. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71979. /**
  71980. * Fired when the secondary button state has changed
  71981. */
  71982. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71983. /**
  71984. * Fired when the pad state has changed
  71985. */
  71986. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71987. /**
  71988. * Fired when controllers stick values have changed
  71989. */
  71990. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71991. /**
  71992. * X and Y axis corrisponding to the controllers joystick
  71993. */
  71994. _this.pad = { x: 0, y: 0 };
  71995. // avoid GC, store state in a tmp object
  71996. _this._changes = {
  71997. pressChanged: false,
  71998. touchChanged: false,
  71999. valueChanged: false,
  72000. changed: false
  72001. };
  72002. _this._buttons = new Array(vrGamepad.buttons.length);
  72003. _this.hand = vrGamepad.hand;
  72004. return _this;
  72005. }
  72006. /**
  72007. * Fired when a controller button's state has changed
  72008. * @param callback the callback containing the button that was modified
  72009. */
  72010. WebVRController.prototype.onButtonStateChange = function (callback) {
  72011. this._onButtonStateChange = callback;
  72012. };
  72013. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  72014. /**
  72015. * The default controller model for the controller
  72016. */
  72017. get: function () {
  72018. return this._defaultModel;
  72019. },
  72020. enumerable: true,
  72021. configurable: true
  72022. });
  72023. /**
  72024. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  72025. */
  72026. WebVRController.prototype.update = function () {
  72027. _super.prototype.update.call(this);
  72028. for (var index = 0; index < this._buttons.length; index++) {
  72029. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  72030. }
  72031. ;
  72032. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  72033. this.pad.x = this.leftStick.x;
  72034. this.pad.y = this.leftStick.y;
  72035. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  72036. }
  72037. };
  72038. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  72039. if (!newState) {
  72040. newState = {
  72041. pressed: false,
  72042. touched: false,
  72043. value: 0
  72044. };
  72045. }
  72046. if (!currentState) {
  72047. this._buttons[buttonIndex] = {
  72048. pressed: newState.pressed,
  72049. touched: newState.touched,
  72050. value: newState.value
  72051. };
  72052. return;
  72053. }
  72054. this._checkChanges(newState, currentState);
  72055. if (this._changes.changed) {
  72056. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  72057. this._handleButtonChange(buttonIndex, newState, this._changes);
  72058. }
  72059. this._buttons[buttonIndex].pressed = newState.pressed;
  72060. this._buttons[buttonIndex].touched = newState.touched;
  72061. // oculus triggers are never 0, thou not touched.
  72062. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  72063. };
  72064. WebVRController.prototype._checkChanges = function (newState, currentState) {
  72065. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  72066. this._changes.touchChanged = newState.touched !== currentState.touched;
  72067. this._changes.valueChanged = newState.value !== currentState.value;
  72068. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  72069. return this._changes;
  72070. };
  72071. /**
  72072. * Disposes of th webVRCOntroller
  72073. */
  72074. WebVRController.prototype.dispose = function () {
  72075. _super.prototype.dispose.call(this);
  72076. this.onTriggerStateChangedObservable.clear();
  72077. this.onMainButtonStateChangedObservable.clear();
  72078. this.onSecondaryButtonStateChangedObservable.clear();
  72079. this.onPadStateChangedObservable.clear();
  72080. this.onPadValuesChangedObservable.clear();
  72081. };
  72082. return WebVRController;
  72083. }(BABYLON.PoseEnabledController));
  72084. BABYLON.WebVRController = WebVRController;
  72085. })(BABYLON || (BABYLON = {}));
  72086. //# sourceMappingURL=babylon.webVRController.js.map
  72087. var BABYLON;
  72088. (function (BABYLON) {
  72089. /**
  72090. * Oculus Touch Controller
  72091. */
  72092. var OculusTouchController = /** @class */ (function (_super) {
  72093. __extends(OculusTouchController, _super);
  72094. /**
  72095. * Creates a new OculusTouchController from a gamepad
  72096. * @param vrGamepad the gamepad that the controller should be created from
  72097. */
  72098. function OculusTouchController(vrGamepad) {
  72099. var _this = _super.call(this, vrGamepad) || this;
  72100. /**
  72101. * Fired when the secondary trigger on this controller is modified
  72102. */
  72103. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  72104. /**
  72105. * Fired when the thumb rest on this controller is modified
  72106. */
  72107. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  72108. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  72109. return _this;
  72110. }
  72111. /**
  72112. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72113. * @param scene scene in which to add meshes
  72114. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72115. */
  72116. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72117. var _this = this;
  72118. var meshName;
  72119. // Hand
  72120. if (this.hand === 'left') {
  72121. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  72122. }
  72123. else { // Right is the default if no hand is specified
  72124. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  72125. }
  72126. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  72127. /*
  72128. Parent Mesh name: oculus_touch_left
  72129. - body
  72130. - trigger
  72131. - thumbstick
  72132. - grip
  72133. - button_y
  72134. - button_x
  72135. - button_enter
  72136. */
  72137. _this._defaultModel = newMeshes[1];
  72138. _this.attachToMesh(_this._defaultModel);
  72139. if (meshLoaded) {
  72140. meshLoaded(_this._defaultModel);
  72141. }
  72142. });
  72143. };
  72144. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  72145. /**
  72146. * Fired when the A button on this controller is modified
  72147. */
  72148. get: function () {
  72149. if (this.hand === 'right') {
  72150. return this.onMainButtonStateChangedObservable;
  72151. }
  72152. else {
  72153. throw new Error('No A button on left hand');
  72154. }
  72155. },
  72156. enumerable: true,
  72157. configurable: true
  72158. });
  72159. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  72160. /**
  72161. * Fired when the B button on this controller is modified
  72162. */
  72163. get: function () {
  72164. if (this.hand === 'right') {
  72165. return this.onSecondaryButtonStateChangedObservable;
  72166. }
  72167. else {
  72168. throw new Error('No B button on left hand');
  72169. }
  72170. },
  72171. enumerable: true,
  72172. configurable: true
  72173. });
  72174. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  72175. /**
  72176. * Fired when the X button on this controller is modified
  72177. */
  72178. get: function () {
  72179. if (this.hand === 'left') {
  72180. return this.onMainButtonStateChangedObservable;
  72181. }
  72182. else {
  72183. throw new Error('No X button on right hand');
  72184. }
  72185. },
  72186. enumerable: true,
  72187. configurable: true
  72188. });
  72189. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  72190. /**
  72191. * Fired when the Y button on this controller is modified
  72192. */
  72193. get: function () {
  72194. if (this.hand === 'left') {
  72195. return this.onSecondaryButtonStateChangedObservable;
  72196. }
  72197. else {
  72198. throw new Error('No Y button on right hand');
  72199. }
  72200. },
  72201. enumerable: true,
  72202. configurable: true
  72203. });
  72204. /**
  72205. * Called once for each button that changed state since the last frame
  72206. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  72207. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  72208. * 2) secondary trigger (same)
  72209. * 3) A (right) X (left), touch, pressed = value
  72210. * 4) B / Y
  72211. * 5) thumb rest
  72212. * @param buttonIdx Which button index changed
  72213. * @param state New state of the button
  72214. * @param changes Which properties on the state changed since last frame
  72215. */
  72216. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72217. var notifyObject = state; //{ state: state, changes: changes };
  72218. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72219. switch (buttonIdx) {
  72220. case 0:
  72221. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72222. return;
  72223. case 1: // index trigger
  72224. if (this._defaultModel) {
  72225. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72226. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72227. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72228. }
  72229. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72230. return;
  72231. case 2: // secondary trigger
  72232. if (this._defaultModel) {
  72233. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72234. }
  72235. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72236. return;
  72237. case 3:
  72238. if (this._defaultModel) {
  72239. if (notifyObject.pressed) {
  72240. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72241. }
  72242. else {
  72243. (this._defaultModel.getChildren()[1]).position.y = 0;
  72244. }
  72245. }
  72246. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72247. return;
  72248. case 4:
  72249. if (this._defaultModel) {
  72250. if (notifyObject.pressed) {
  72251. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72252. }
  72253. else {
  72254. (this._defaultModel.getChildren()[2]).position.y = 0;
  72255. }
  72256. }
  72257. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72258. return;
  72259. case 5:
  72260. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72261. return;
  72262. }
  72263. };
  72264. /**
  72265. * Base Url for the controller model.
  72266. */
  72267. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72268. /**
  72269. * File name for the left controller model.
  72270. */
  72271. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72272. /**
  72273. * File name for the right controller model.
  72274. */
  72275. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72276. return OculusTouchController;
  72277. }(BABYLON.WebVRController));
  72278. BABYLON.OculusTouchController = OculusTouchController;
  72279. })(BABYLON || (BABYLON = {}));
  72280. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72281. var BABYLON;
  72282. (function (BABYLON) {
  72283. /**
  72284. * Vive Controller
  72285. */
  72286. var ViveController = /** @class */ (function (_super) {
  72287. __extends(ViveController, _super);
  72288. /**
  72289. * Creates a new ViveController from a gamepad
  72290. * @param vrGamepad the gamepad that the controller should be created from
  72291. */
  72292. function ViveController(vrGamepad) {
  72293. var _this = _super.call(this, vrGamepad) || this;
  72294. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72295. _this._invertLeftStickY = true;
  72296. return _this;
  72297. }
  72298. /**
  72299. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72300. * @param scene scene in which to add meshes
  72301. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72302. */
  72303. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72304. var _this = this;
  72305. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72306. /*
  72307. Parent Mesh name: ViveWand
  72308. - body
  72309. - r_gripper
  72310. - l_gripper
  72311. - menu_button
  72312. - system_button
  72313. - trackpad
  72314. - trigger
  72315. - LED
  72316. */
  72317. _this._defaultModel = newMeshes[1];
  72318. _this.attachToMesh(_this._defaultModel);
  72319. if (meshLoaded) {
  72320. meshLoaded(_this._defaultModel);
  72321. }
  72322. });
  72323. };
  72324. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72325. /**
  72326. * Fired when the left button on this controller is modified
  72327. */
  72328. get: function () {
  72329. return this.onMainButtonStateChangedObservable;
  72330. },
  72331. enumerable: true,
  72332. configurable: true
  72333. });
  72334. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72335. /**
  72336. * Fired when the right button on this controller is modified
  72337. */
  72338. get: function () {
  72339. return this.onMainButtonStateChangedObservable;
  72340. },
  72341. enumerable: true,
  72342. configurable: true
  72343. });
  72344. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72345. /**
  72346. * Fired when the menu button on this controller is modified
  72347. */
  72348. get: function () {
  72349. return this.onSecondaryButtonStateChangedObservable;
  72350. },
  72351. enumerable: true,
  72352. configurable: true
  72353. });
  72354. /**
  72355. * Called once for each button that changed state since the last frame
  72356. * Vive mapping:
  72357. * 0: touchpad
  72358. * 1: trigger
  72359. * 2: left AND right buttons
  72360. * 3: menu button
  72361. * @param buttonIdx Which button index changed
  72362. * @param state New state of the button
  72363. * @param changes Which properties on the state changed since last frame
  72364. */
  72365. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72366. var notifyObject = state; //{ state: state, changes: changes };
  72367. switch (buttonIdx) {
  72368. case 0:
  72369. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72370. return;
  72371. case 1: // index trigger
  72372. if (this._defaultModel) {
  72373. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72374. }
  72375. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72376. return;
  72377. case 2: // left AND right button
  72378. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72379. return;
  72380. case 3:
  72381. if (this._defaultModel) {
  72382. if (notifyObject.pressed) {
  72383. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72384. }
  72385. else {
  72386. (this._defaultModel.getChildren()[2]).position.y = 0;
  72387. }
  72388. }
  72389. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72390. return;
  72391. }
  72392. };
  72393. /**
  72394. * Base Url for the controller model.
  72395. */
  72396. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72397. /**
  72398. * File name for the controller model.
  72399. */
  72400. ViveController.MODEL_FILENAME = 'wand.babylon';
  72401. return ViveController;
  72402. }(BABYLON.WebVRController));
  72403. BABYLON.ViveController = ViveController;
  72404. })(BABYLON || (BABYLON = {}));
  72405. //# sourceMappingURL=babylon.viveController.js.map
  72406. var BABYLON;
  72407. (function (BABYLON) {
  72408. /**
  72409. * Generic Controller
  72410. */
  72411. var GenericController = /** @class */ (function (_super) {
  72412. __extends(GenericController, _super);
  72413. /**
  72414. * Creates a new GenericController from a gamepad
  72415. * @param vrGamepad the gamepad that the controller should be created from
  72416. */
  72417. function GenericController(vrGamepad) {
  72418. return _super.call(this, vrGamepad) || this;
  72419. }
  72420. /**
  72421. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72422. * @param scene scene in which to add meshes
  72423. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72424. */
  72425. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72426. var _this = this;
  72427. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72428. _this._defaultModel = newMeshes[1];
  72429. _this.attachToMesh(_this._defaultModel);
  72430. if (meshLoaded) {
  72431. meshLoaded(_this._defaultModel);
  72432. }
  72433. });
  72434. };
  72435. /**
  72436. * Called once for each button that changed state since the last frame
  72437. * @param buttonIdx Which button index changed
  72438. * @param state New state of the button
  72439. * @param changes Which properties on the state changed since last frame
  72440. */
  72441. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72442. console.log("Button id: " + buttonIdx + "state: ");
  72443. console.dir(state);
  72444. };
  72445. /**
  72446. * Base Url for the controller model.
  72447. */
  72448. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72449. /**
  72450. * File name for the controller model.
  72451. */
  72452. GenericController.MODEL_FILENAME = 'generic.babylon';
  72453. return GenericController;
  72454. }(BABYLON.WebVRController));
  72455. BABYLON.GenericController = GenericController;
  72456. })(BABYLON || (BABYLON = {}));
  72457. //# sourceMappingURL=babylon.genericController.js.map
  72458. var BABYLON;
  72459. (function (BABYLON) {
  72460. /**
  72461. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72462. */
  72463. var LoadedMeshInfo = /** @class */ (function () {
  72464. function LoadedMeshInfo() {
  72465. /**
  72466. * Map of the button meshes contained in the controller
  72467. */
  72468. this.buttonMeshes = {};
  72469. /**
  72470. * Map of the axis meshes contained in the controller
  72471. */
  72472. this.axisMeshes = {};
  72473. }
  72474. return LoadedMeshInfo;
  72475. }());
  72476. /**
  72477. * Defines the WindowsMotionController object that the state of the windows motion controller
  72478. */
  72479. var WindowsMotionController = /** @class */ (function (_super) {
  72480. __extends(WindowsMotionController, _super);
  72481. /**
  72482. * Creates a new WindowsMotionController from a gamepad
  72483. * @param vrGamepad the gamepad that the controller should be created from
  72484. */
  72485. function WindowsMotionController(vrGamepad) {
  72486. var _this = _super.call(this, vrGamepad) || this;
  72487. _this._mapping = {
  72488. // Semantic button names
  72489. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72490. // A mapping of the button name to glTF model node name
  72491. // that should be transformed by button value.
  72492. buttonMeshNames: {
  72493. 'trigger': 'SELECT',
  72494. 'menu': 'MENU',
  72495. 'grip': 'GRASP',
  72496. 'thumbstick': 'THUMBSTICK_PRESS',
  72497. 'trackpad': 'TOUCHPAD_PRESS'
  72498. },
  72499. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72500. buttonObservableNames: {
  72501. 'trigger': 'onTriggerStateChangedObservable',
  72502. 'menu': 'onSecondaryButtonStateChangedObservable',
  72503. 'grip': 'onMainButtonStateChangedObservable',
  72504. 'thumbstick': 'onPadStateChangedObservable',
  72505. 'trackpad': 'onTrackpadChangedObservable'
  72506. },
  72507. // A mapping of the axis name to glTF model node name
  72508. // that should be transformed by axis value.
  72509. // This array mirrors the browserGamepad.axes array, such that
  72510. // the mesh corresponding to axis 0 is in this array index 0.
  72511. axisMeshNames: [
  72512. 'THUMBSTICK_X',
  72513. 'THUMBSTICK_Y',
  72514. 'TOUCHPAD_TOUCH_X',
  72515. 'TOUCHPAD_TOUCH_Y'
  72516. ],
  72517. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72518. };
  72519. /**
  72520. * Fired when the trackpad on this controller is clicked
  72521. */
  72522. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72523. /**
  72524. * Fired when the trackpad on this controller is modified
  72525. */
  72526. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72527. /**
  72528. * The current x and y values of this controller's trackpad
  72529. */
  72530. _this.trackpad = { x: 0, y: 0 };
  72531. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72532. _this._loadedMeshInfo = null;
  72533. return _this;
  72534. }
  72535. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72536. /**
  72537. * Fired when the trigger on this controller is modified
  72538. */
  72539. get: function () {
  72540. return this.onTriggerStateChangedObservable;
  72541. },
  72542. enumerable: true,
  72543. configurable: true
  72544. });
  72545. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72546. /**
  72547. * Fired when the menu button on this controller is modified
  72548. */
  72549. get: function () {
  72550. return this.onSecondaryButtonStateChangedObservable;
  72551. },
  72552. enumerable: true,
  72553. configurable: true
  72554. });
  72555. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72556. /**
  72557. * Fired when the grip button on this controller is modified
  72558. */
  72559. get: function () {
  72560. return this.onMainButtonStateChangedObservable;
  72561. },
  72562. enumerable: true,
  72563. configurable: true
  72564. });
  72565. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72566. /**
  72567. * Fired when the thumbstick button on this controller is modified
  72568. */
  72569. get: function () {
  72570. return this.onPadStateChangedObservable;
  72571. },
  72572. enumerable: true,
  72573. configurable: true
  72574. });
  72575. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72576. /**
  72577. * Fired when the touchpad button on this controller is modified
  72578. */
  72579. get: function () {
  72580. return this.onTrackpadChangedObservable;
  72581. },
  72582. enumerable: true,
  72583. configurable: true
  72584. });
  72585. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72586. /**
  72587. * Fired when the touchpad values on this controller are modified
  72588. */
  72589. get: function () {
  72590. return this.onTrackpadValuesChangedObservable;
  72591. },
  72592. enumerable: true,
  72593. configurable: true
  72594. });
  72595. WindowsMotionController.prototype._updateTrackpad = function () {
  72596. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72597. this.trackpad.x = this.browserGamepad["axes"][2];
  72598. this.trackpad.y = this.browserGamepad["axes"][3];
  72599. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72600. }
  72601. };
  72602. /**
  72603. * Called once per frame by the engine.
  72604. */
  72605. WindowsMotionController.prototype.update = function () {
  72606. _super.prototype.update.call(this);
  72607. if (this.browserGamepad.axes) {
  72608. this._updateTrackpad();
  72609. // Only need to animate axes if there is a loaded mesh
  72610. if (this._loadedMeshInfo) {
  72611. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72612. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72613. }
  72614. }
  72615. }
  72616. };
  72617. /**
  72618. * Called once for each button that changed state since the last frame
  72619. * @param buttonIdx Which button index changed
  72620. * @param state New state of the button
  72621. * @param changes Which properties on the state changed since last frame
  72622. */
  72623. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72624. var buttonName = this._mapping.buttons[buttonIdx];
  72625. if (!buttonName) {
  72626. return;
  72627. }
  72628. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72629. this._updateTrackpad();
  72630. // Only emit events for buttons that we know how to map from index to name
  72631. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72632. if (observable) {
  72633. observable.notifyObservers(state);
  72634. }
  72635. this._lerpButtonTransform(buttonName, state.value);
  72636. };
  72637. /**
  72638. * Moves the buttons on the controller mesh based on their current state
  72639. * @param buttonName the name of the button to move
  72640. * @param buttonValue the value of the button which determines the buttons new position
  72641. */
  72642. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72643. // If there is no loaded mesh, there is nothing to transform.
  72644. if (!this._loadedMeshInfo) {
  72645. return;
  72646. }
  72647. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72648. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72649. return;
  72650. }
  72651. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72652. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72653. };
  72654. /**
  72655. * Moves the axis on the controller mesh based on its current state
  72656. * @param axis the index of the axis
  72657. * @param axisValue the value of the axis which determines the meshes new position
  72658. * @hidden
  72659. */
  72660. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72661. if (!this._loadedMeshInfo) {
  72662. return;
  72663. }
  72664. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72665. if (!meshInfo) {
  72666. return;
  72667. }
  72668. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72669. return;
  72670. }
  72671. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72672. var lerpValue = axisValue * 0.5 + 0.5;
  72673. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72674. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72675. };
  72676. /**
  72677. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72678. * @param scene scene in which to add meshes
  72679. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72680. */
  72681. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72682. var _this = this;
  72683. if (forceDefault === void 0) { forceDefault = false; }
  72684. var path;
  72685. var filename;
  72686. // Checking if GLB loader is present
  72687. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72688. // Determine the device specific folder based on the ID suffix
  72689. var device = 'default';
  72690. if (this.id && !forceDefault) {
  72691. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72692. device = ((match && match[0]) || device);
  72693. }
  72694. // Hand
  72695. if (this.hand === 'left') {
  72696. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72697. }
  72698. else { // Right is the default if no hand is specified
  72699. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72700. }
  72701. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72702. }
  72703. else {
  72704. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72705. path = BABYLON.GenericController.MODEL_BASE_URL;
  72706. filename = BABYLON.GenericController.MODEL_FILENAME;
  72707. }
  72708. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72709. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72710. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72711. if (!_this._loadedMeshInfo) {
  72712. return;
  72713. }
  72714. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72715. _this.attachToMesh(_this._defaultModel);
  72716. if (meshLoaded) {
  72717. meshLoaded(_this._defaultModel);
  72718. }
  72719. }, null, function (scene, message) {
  72720. BABYLON.Tools.Log(message);
  72721. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72722. if (!forceDefault) {
  72723. _this.initControllerMesh(scene, meshLoaded, true);
  72724. }
  72725. });
  72726. };
  72727. /**
  72728. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72729. * can be transformed by button presses and axes values, based on this._mapping.
  72730. *
  72731. * @param scene scene in which the meshes exist
  72732. * @param meshes list of meshes that make up the controller model to process
  72733. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72734. */
  72735. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72736. var loadedMeshInfo = null;
  72737. // Create a new mesh to contain the glTF hierarchy
  72738. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72739. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72740. var childMesh = null;
  72741. for (var i = 0; i < meshes.length; i++) {
  72742. var mesh = meshes[i];
  72743. if (!mesh.parent) {
  72744. // Exclude controller meshes from picking results
  72745. mesh.isPickable = false;
  72746. // Handle root node, attach to the new parentMesh
  72747. childMesh = mesh;
  72748. break;
  72749. }
  72750. }
  72751. if (childMesh) {
  72752. childMesh.setParent(parentMesh);
  72753. // Create our mesh info. Note that this method will always return non-null.
  72754. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72755. }
  72756. else {
  72757. BABYLON.Tools.Warn('Could not find root node in model file.');
  72758. }
  72759. return loadedMeshInfo;
  72760. };
  72761. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72762. var loadedMeshInfo = new LoadedMeshInfo();
  72763. var i;
  72764. loadedMeshInfo.rootNode = rootNode;
  72765. // Reset the caches
  72766. loadedMeshInfo.buttonMeshes = {};
  72767. loadedMeshInfo.axisMeshes = {};
  72768. // Button Meshes
  72769. for (i = 0; i < this._mapping.buttons.length; i++) {
  72770. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72771. if (!buttonMeshName) {
  72772. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72773. continue;
  72774. }
  72775. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72776. if (!buttonMesh) {
  72777. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72778. continue;
  72779. }
  72780. var buttonMeshInfo = {
  72781. index: i,
  72782. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72783. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72784. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72785. };
  72786. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72787. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72788. }
  72789. else {
  72790. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72791. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72792. '(VALUE: ' + !!buttonMeshInfo.value +
  72793. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72794. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72795. ')');
  72796. }
  72797. }
  72798. // Axis Meshes
  72799. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72800. var axisMeshName = this._mapping.axisMeshNames[i];
  72801. if (!axisMeshName) {
  72802. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72803. continue;
  72804. }
  72805. var axisMesh = getChildByName(rootNode, axisMeshName);
  72806. if (!axisMesh) {
  72807. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72808. continue;
  72809. }
  72810. var axisMeshInfo = {
  72811. index: i,
  72812. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72813. min: getImmediateChildByName(axisMesh, 'MIN'),
  72814. max: getImmediateChildByName(axisMesh, 'MAX')
  72815. };
  72816. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72817. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72818. }
  72819. else {
  72820. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72821. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72822. '(VALUE: ' + !!axisMeshInfo.value +
  72823. ', MIN: ' + !!axisMeshInfo.min +
  72824. ', MAX:' + !!axisMeshInfo.max +
  72825. ')');
  72826. }
  72827. }
  72828. // Pointing Ray
  72829. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72830. if (!loadedMeshInfo.pointingPoseNode) {
  72831. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72832. }
  72833. else {
  72834. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  72835. }
  72836. return loadedMeshInfo;
  72837. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72838. function getChildByName(node, name) {
  72839. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72840. }
  72841. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72842. function getImmediateChildByName(node, name) {
  72843. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72844. }
  72845. };
  72846. /**
  72847. * Gets the ray of the controller in the direction the controller is pointing
  72848. * @param length the length the resulting ray should be
  72849. * @returns a ray in the direction the controller is pointing
  72850. */
  72851. WindowsMotionController.prototype.getForwardRay = function (length) {
  72852. if (length === void 0) { length = 100; }
  72853. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72854. return _super.prototype.getForwardRay.call(this, length);
  72855. }
  72856. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72857. var origin = m.getTranslation();
  72858. var forward = new BABYLON.Vector3(0, 0, -1);
  72859. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72860. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72861. return new BABYLON.Ray(origin, direction, length);
  72862. };
  72863. /**
  72864. * Disposes of the controller
  72865. */
  72866. WindowsMotionController.prototype.dispose = function () {
  72867. _super.prototype.dispose.call(this);
  72868. this.onTrackpadChangedObservable.clear();
  72869. };
  72870. /**
  72871. * The base url used to load the left and right controller models
  72872. */
  72873. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72874. /**
  72875. * The name of the left controller model file
  72876. */
  72877. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72878. /**
  72879. * The name of the right controller model file
  72880. */
  72881. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72882. /**
  72883. * The controller name prefix for this controller type
  72884. */
  72885. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72886. /**
  72887. * The controller id pattern for this controller type
  72888. */
  72889. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72890. return WindowsMotionController;
  72891. }(BABYLON.WebVRController));
  72892. BABYLON.WindowsMotionController = WindowsMotionController;
  72893. })(BABYLON || (BABYLON = {}));
  72894. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72895. var BABYLON;
  72896. (function (BABYLON) {
  72897. /**
  72898. * Gear VR Controller
  72899. */
  72900. var GearVRController = /** @class */ (function (_super) {
  72901. __extends(GearVRController, _super);
  72902. /**
  72903. * Creates a new GearVRController from a gamepad
  72904. * @param vrGamepad the gamepad that the controller should be created from
  72905. */
  72906. function GearVRController(vrGamepad) {
  72907. var _this = _super.call(this, vrGamepad) || this;
  72908. _this._buttonIndexToObservableNameMap = [
  72909. 'onTrackpadChangedObservable',
  72910. 'onTriggerStateChangedObservable' // Trigger
  72911. ];
  72912. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72913. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72914. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72915. return _this;
  72916. }
  72917. /**
  72918. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72919. * @param scene scene in which to add meshes
  72920. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72921. */
  72922. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72923. var _this = this;
  72924. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72925. _this._defaultModel = newMeshes[1];
  72926. _this.attachToMesh(_this._defaultModel);
  72927. if (meshLoaded) {
  72928. meshLoaded(_this._defaultModel);
  72929. }
  72930. });
  72931. };
  72932. /**
  72933. * Called once for each button that changed state since the last frame
  72934. * @param buttonIdx Which button index changed
  72935. * @param state New state of the button
  72936. * @param changes Which properties on the state changed since last frame
  72937. */
  72938. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72939. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72940. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72941. // Only emit events for buttons that we know how to map from index to observable
  72942. var observable = this[observableName];
  72943. if (observable) {
  72944. observable.notifyObservers(state);
  72945. }
  72946. }
  72947. };
  72948. /**
  72949. * Base Url for the controller model.
  72950. */
  72951. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72952. /**
  72953. * File name for the controller model.
  72954. */
  72955. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72956. /**
  72957. * Gamepad Id prefix used to identify this controller.
  72958. */
  72959. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72960. return GearVRController;
  72961. }(BABYLON.WebVRController));
  72962. BABYLON.GearVRController = GearVRController;
  72963. })(BABYLON || (BABYLON = {}));
  72964. //# sourceMappingURL=babylon.gearVRController.js.map
  72965. var BABYLON;
  72966. (function (BABYLON) {
  72967. /**
  72968. * Google Daydream controller
  72969. */
  72970. var DaydreamController = /** @class */ (function (_super) {
  72971. __extends(DaydreamController, _super);
  72972. /**
  72973. * Creates a new DaydreamController from a gamepad
  72974. * @param vrGamepad the gamepad that the controller should be created from
  72975. */
  72976. function DaydreamController(vrGamepad) {
  72977. var _this = _super.call(this, vrGamepad) || this;
  72978. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72979. return _this;
  72980. }
  72981. /**
  72982. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72983. * @param scene scene in which to add meshes
  72984. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72985. */
  72986. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72987. var _this = this;
  72988. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72989. _this._defaultModel = newMeshes[1];
  72990. _this.attachToMesh(_this._defaultModel);
  72991. if (meshLoaded) {
  72992. meshLoaded(_this._defaultModel);
  72993. }
  72994. });
  72995. };
  72996. /**
  72997. * Called once for each button that changed state since the last frame
  72998. * @param buttonIdx Which button index changed
  72999. * @param state New state of the button
  73000. * @param changes Which properties on the state changed since last frame
  73001. */
  73002. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73003. // Daydream controller only has 1 GamepadButton (on the trackpad).
  73004. if (buttonIdx === 0) {
  73005. var observable = this.onTriggerStateChangedObservable;
  73006. if (observable) {
  73007. observable.notifyObservers(state);
  73008. }
  73009. }
  73010. else {
  73011. // If the app or home buttons are ever made available
  73012. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  73013. }
  73014. };
  73015. /**
  73016. * Base Url for the controller model.
  73017. */
  73018. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73019. /**
  73020. * File name for the controller model.
  73021. */
  73022. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  73023. /**
  73024. * Gamepad Id prefix used to identify Daydream Controller.
  73025. */
  73026. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  73027. return DaydreamController;
  73028. }(BABYLON.WebVRController));
  73029. BABYLON.DaydreamController = DaydreamController;
  73030. })(BABYLON || (BABYLON = {}));
  73031. //# sourceMappingURL=babylon.daydreamController.js.map
  73032. var BABYLON;
  73033. (function (BABYLON) {
  73034. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  73035. get: function () {
  73036. if (!this._gamepadManager) {
  73037. this._gamepadManager = new BABYLON.GamepadManager(this);
  73038. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  73039. if (!component) {
  73040. component = new GamepadSystemSceneComponent(this);
  73041. this._addComponent(component);
  73042. }
  73043. }
  73044. return this._gamepadManager;
  73045. },
  73046. enumerable: true,
  73047. configurable: true
  73048. });
  73049. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  73050. this.add(new BABYLON.FreeCameraGamepadInput());
  73051. return this;
  73052. };
  73053. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  73054. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  73055. return this;
  73056. };
  73057. /**
  73058. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  73059. */
  73060. var GamepadSystemSceneComponent = /** @class */ (function () {
  73061. /**
  73062. * Creates a new instance of the component for the given scene
  73063. * @param scene Defines the scene to register the component in
  73064. */
  73065. function GamepadSystemSceneComponent(scene) {
  73066. /**
  73067. * The component name helpfull to identify the component in the list of scene components.
  73068. */
  73069. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  73070. this.scene = scene;
  73071. }
  73072. /**
  73073. * Registers the component in a given scene
  73074. */
  73075. GamepadSystemSceneComponent.prototype.register = function () {
  73076. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  73077. };
  73078. /**
  73079. * Rebuilds the elements related to this component in case of
  73080. * context lost for instance.
  73081. */
  73082. GamepadSystemSceneComponent.prototype.rebuild = function () {
  73083. // Nothing to do for gamepads
  73084. };
  73085. /**
  73086. * Disposes the component and the associated ressources
  73087. */
  73088. GamepadSystemSceneComponent.prototype.dispose = function () {
  73089. var gamepadManager = this.scene._gamepadManager;
  73090. if (gamepadManager) {
  73091. gamepadManager.dispose();
  73092. this.scene._gamepadManager = null;
  73093. }
  73094. };
  73095. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  73096. var gamepadManager = this.scene._gamepadManager;
  73097. if (gamepadManager && gamepadManager._isMonitoring) {
  73098. gamepadManager._checkGamepadsStatus();
  73099. }
  73100. };
  73101. return GamepadSystemSceneComponent;
  73102. }());
  73103. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  73104. })(BABYLON || (BABYLON = {}));
  73105. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  73106. var BABYLON;
  73107. (function (BABYLON) {
  73108. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  73109. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  73110. });
  73111. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  73112. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  73113. });
  73114. var FollowCamera = /** @class */ (function (_super) {
  73115. __extends(FollowCamera, _super);
  73116. function FollowCamera(name, position, scene, lockedTarget) {
  73117. if (lockedTarget === void 0) { lockedTarget = null; }
  73118. var _this = _super.call(this, name, position, scene) || this;
  73119. _this.radius = 12;
  73120. _this.rotationOffset = 0;
  73121. _this.heightOffset = 4;
  73122. _this.cameraAcceleration = 0.05;
  73123. _this.maxCameraSpeed = 20;
  73124. _this.lockedTarget = lockedTarget;
  73125. return _this;
  73126. }
  73127. FollowCamera.prototype.getRadians = function (degrees) {
  73128. return degrees * Math.PI / 180;
  73129. };
  73130. FollowCamera.prototype.follow = function (cameraTarget) {
  73131. if (!cameraTarget)
  73132. return;
  73133. var yRotation;
  73134. if (cameraTarget.rotationQuaternion) {
  73135. var rotMatrix = new BABYLON.Matrix();
  73136. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  73137. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  73138. }
  73139. else {
  73140. yRotation = cameraTarget.rotation.y;
  73141. }
  73142. var radians = this.getRadians(this.rotationOffset) + yRotation;
  73143. var targetPosition = cameraTarget.getAbsolutePosition();
  73144. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  73145. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  73146. var dx = targetX - this.position.x;
  73147. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  73148. var dz = (targetZ) - this.position.z;
  73149. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  73150. var vy = dy * this.cameraAcceleration;
  73151. var vz = dz * this.cameraAcceleration * 2;
  73152. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  73153. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73154. }
  73155. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  73156. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73157. }
  73158. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  73159. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73160. }
  73161. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  73162. this.setTarget(targetPosition);
  73163. };
  73164. FollowCamera.prototype._checkInputs = function () {
  73165. _super.prototype._checkInputs.call(this);
  73166. if (this.lockedTarget) {
  73167. this.follow(this.lockedTarget);
  73168. }
  73169. };
  73170. FollowCamera.prototype.getClassName = function () {
  73171. return "FollowCamera";
  73172. };
  73173. __decorate([
  73174. BABYLON.serialize()
  73175. ], FollowCamera.prototype, "radius", void 0);
  73176. __decorate([
  73177. BABYLON.serialize()
  73178. ], FollowCamera.prototype, "rotationOffset", void 0);
  73179. __decorate([
  73180. BABYLON.serialize()
  73181. ], FollowCamera.prototype, "heightOffset", void 0);
  73182. __decorate([
  73183. BABYLON.serialize()
  73184. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  73185. __decorate([
  73186. BABYLON.serialize()
  73187. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  73188. __decorate([
  73189. BABYLON.serializeAsMeshReference("lockedTargetId")
  73190. ], FollowCamera.prototype, "lockedTarget", void 0);
  73191. return FollowCamera;
  73192. }(BABYLON.TargetCamera));
  73193. BABYLON.FollowCamera = FollowCamera;
  73194. var ArcFollowCamera = /** @class */ (function (_super) {
  73195. __extends(ArcFollowCamera, _super);
  73196. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  73197. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  73198. _this.alpha = alpha;
  73199. _this.beta = beta;
  73200. _this.radius = radius;
  73201. _this.target = target;
  73202. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  73203. _this.follow();
  73204. return _this;
  73205. }
  73206. ArcFollowCamera.prototype.follow = function () {
  73207. if (!this.target) {
  73208. return;
  73209. }
  73210. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  73211. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  73212. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  73213. var targetPosition = this.target.getAbsolutePosition();
  73214. this.position = targetPosition.add(this._cartesianCoordinates);
  73215. this.setTarget(targetPosition);
  73216. };
  73217. ArcFollowCamera.prototype._checkInputs = function () {
  73218. _super.prototype._checkInputs.call(this);
  73219. this.follow();
  73220. };
  73221. ArcFollowCamera.prototype.getClassName = function () {
  73222. return "ArcFollowCamera";
  73223. };
  73224. return ArcFollowCamera;
  73225. }(BABYLON.TargetCamera));
  73226. BABYLON.ArcFollowCamera = ArcFollowCamera;
  73227. })(BABYLON || (BABYLON = {}));
  73228. //# sourceMappingURL=babylon.followCamera.js.map
  73229. var BABYLON;
  73230. (function (BABYLON) {
  73231. // We're mainly based on the logic defined into the FreeCamera code
  73232. var UniversalCamera = /** @class */ (function (_super) {
  73233. __extends(UniversalCamera, _super);
  73234. //-- end properties for backward compatibility for inputs
  73235. function UniversalCamera(name, position, scene) {
  73236. var _this = _super.call(this, name, position, scene) || this;
  73237. _this.inputs.addGamepad();
  73238. return _this;
  73239. }
  73240. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  73241. //-- Begin properties for backward compatibility for inputs
  73242. get: function () {
  73243. var gamepad = this.inputs.attached["gamepad"];
  73244. if (gamepad)
  73245. return gamepad.gamepadAngularSensibility;
  73246. return 0;
  73247. },
  73248. set: function (value) {
  73249. var gamepad = this.inputs.attached["gamepad"];
  73250. if (gamepad)
  73251. gamepad.gamepadAngularSensibility = value;
  73252. },
  73253. enumerable: true,
  73254. configurable: true
  73255. });
  73256. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  73257. get: function () {
  73258. var gamepad = this.inputs.attached["gamepad"];
  73259. if (gamepad)
  73260. return gamepad.gamepadMoveSensibility;
  73261. return 0;
  73262. },
  73263. set: function (value) {
  73264. var gamepad = this.inputs.attached["gamepad"];
  73265. if (gamepad)
  73266. gamepad.gamepadMoveSensibility = value;
  73267. },
  73268. enumerable: true,
  73269. configurable: true
  73270. });
  73271. UniversalCamera.prototype.getClassName = function () {
  73272. return "UniversalCamera";
  73273. };
  73274. return UniversalCamera;
  73275. }(BABYLON.TouchCamera));
  73276. BABYLON.UniversalCamera = UniversalCamera;
  73277. })(BABYLON || (BABYLON = {}));
  73278. //# sourceMappingURL=babylon.universalCamera.js.map
  73279. var BABYLON;
  73280. (function (BABYLON) {
  73281. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  73282. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  73283. });
  73284. // We're mainly based on the logic defined into the FreeCamera code
  73285. var GamepadCamera = /** @class */ (function (_super) {
  73286. __extends(GamepadCamera, _super);
  73287. //-- end properties for backward compatibility for inputs
  73288. function GamepadCamera(name, position, scene) {
  73289. return _super.call(this, name, position, scene) || this;
  73290. }
  73291. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  73292. //-- Begin properties for backward compatibility for inputs
  73293. get: function () {
  73294. var gamepad = this.inputs.attached["gamepad"];
  73295. if (gamepad)
  73296. return gamepad.gamepadAngularSensibility;
  73297. return 0;
  73298. },
  73299. set: function (value) {
  73300. var gamepad = this.inputs.attached["gamepad"];
  73301. if (gamepad)
  73302. gamepad.gamepadAngularSensibility = value;
  73303. },
  73304. enumerable: true,
  73305. configurable: true
  73306. });
  73307. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  73308. get: function () {
  73309. var gamepad = this.inputs.attached["gamepad"];
  73310. if (gamepad)
  73311. return gamepad.gamepadMoveSensibility;
  73312. return 0;
  73313. },
  73314. set: function (value) {
  73315. var gamepad = this.inputs.attached["gamepad"];
  73316. if (gamepad)
  73317. gamepad.gamepadMoveSensibility = value;
  73318. },
  73319. enumerable: true,
  73320. configurable: true
  73321. });
  73322. GamepadCamera.prototype.getClassName = function () {
  73323. return "GamepadCamera";
  73324. };
  73325. return GamepadCamera;
  73326. }(BABYLON.UniversalCamera));
  73327. BABYLON.GamepadCamera = GamepadCamera;
  73328. })(BABYLON || (BABYLON = {}));
  73329. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73330. var BABYLON;
  73331. (function (BABYLON) {
  73332. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73333. function PostProcessRenderPipelineManager() {
  73334. this._renderPipelines = {};
  73335. }
  73336. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73337. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73338. };
  73339. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73340. if (unique === void 0) { unique = false; }
  73341. var renderPipeline = this._renderPipelines[renderPipelineName];
  73342. if (!renderPipeline) {
  73343. return;
  73344. }
  73345. renderPipeline._attachCameras(cameras, unique);
  73346. };
  73347. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73348. var renderPipeline = this._renderPipelines[renderPipelineName];
  73349. if (!renderPipeline) {
  73350. return;
  73351. }
  73352. renderPipeline._detachCameras(cameras);
  73353. };
  73354. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73355. var renderPipeline = this._renderPipelines[renderPipelineName];
  73356. if (!renderPipeline) {
  73357. return;
  73358. }
  73359. renderPipeline._enableEffect(renderEffectName, cameras);
  73360. };
  73361. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73362. var renderPipeline = this._renderPipelines[renderPipelineName];
  73363. if (!renderPipeline) {
  73364. return;
  73365. }
  73366. renderPipeline._disableEffect(renderEffectName, cameras);
  73367. };
  73368. PostProcessRenderPipelineManager.prototype.update = function () {
  73369. for (var renderPipelineName in this._renderPipelines) {
  73370. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73371. var pipeline = this._renderPipelines[renderPipelineName];
  73372. if (!pipeline.isSupported) {
  73373. pipeline.dispose();
  73374. delete this._renderPipelines[renderPipelineName];
  73375. }
  73376. else {
  73377. pipeline._update();
  73378. }
  73379. }
  73380. }
  73381. };
  73382. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73383. for (var renderPipelineName in this._renderPipelines) {
  73384. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73385. var pipeline = this._renderPipelines[renderPipelineName];
  73386. pipeline._rebuild();
  73387. }
  73388. }
  73389. };
  73390. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73391. for (var renderPipelineName in this._renderPipelines) {
  73392. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73393. var pipeline = this._renderPipelines[renderPipelineName];
  73394. pipeline.dispose();
  73395. }
  73396. }
  73397. };
  73398. return PostProcessRenderPipelineManager;
  73399. }());
  73400. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73401. })(BABYLON || (BABYLON = {}));
  73402. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73403. var BABYLON;
  73404. (function (BABYLON) {
  73405. /**
  73406. * This represents a set of one or more post processes in Babylon.
  73407. * A post process can be used to apply a shader to a texture after it is rendered.
  73408. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73409. */
  73410. var PostProcessRenderEffect = /** @class */ (function () {
  73411. /**
  73412. * Instantiates a post process render effect.
  73413. * A post process can be used to apply a shader to a texture after it is rendered.
  73414. * @param engine The engine the effect is tied to
  73415. * @param name The name of the effect
  73416. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73417. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73418. */
  73419. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73420. this._name = name;
  73421. this._singleInstance = singleInstance || true;
  73422. this._getPostProcesses = getPostProcesses;
  73423. this._cameras = {};
  73424. this._indicesForCamera = {};
  73425. this._postProcesses = {};
  73426. }
  73427. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73428. /**
  73429. * Checks if all the post processes in the effect are supported.
  73430. */
  73431. get: function () {
  73432. for (var index in this._postProcesses) {
  73433. if (this._postProcesses.hasOwnProperty(index)) {
  73434. var pps = this._postProcesses[index];
  73435. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73436. if (!pps[ppIndex].isSupported) {
  73437. return false;
  73438. }
  73439. }
  73440. }
  73441. }
  73442. return true;
  73443. },
  73444. enumerable: true,
  73445. configurable: true
  73446. });
  73447. /**
  73448. * Updates the current state of the effect
  73449. */
  73450. PostProcessRenderEffect.prototype._update = function () {
  73451. };
  73452. /**
  73453. * Attaches the effect on cameras
  73454. * @param cameras The camera to attach to.
  73455. */
  73456. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73457. var _this = this;
  73458. var cameraKey;
  73459. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73460. if (!cams) {
  73461. return;
  73462. }
  73463. for (var i = 0; i < cams.length; i++) {
  73464. var camera = cams[i];
  73465. var cameraName = camera.name;
  73466. if (this._singleInstance) {
  73467. cameraKey = 0;
  73468. }
  73469. else {
  73470. cameraKey = cameraName;
  73471. }
  73472. if (!this._postProcesses[cameraKey]) {
  73473. var postProcess = this._getPostProcesses();
  73474. if (postProcess) {
  73475. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73476. }
  73477. }
  73478. if (!this._indicesForCamera[cameraName]) {
  73479. this._indicesForCamera[cameraName] = [];
  73480. }
  73481. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73482. var index = camera.attachPostProcess(postProcess);
  73483. _this._indicesForCamera[cameraName].push(index);
  73484. });
  73485. if (!this._cameras[cameraName]) {
  73486. this._cameras[cameraName] = camera;
  73487. }
  73488. }
  73489. };
  73490. /**
  73491. * Detatches the effect on cameras
  73492. * @param cameras The camera to detatch from.
  73493. */
  73494. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73495. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73496. if (!cams) {
  73497. return;
  73498. }
  73499. for (var i = 0; i < cams.length; i++) {
  73500. var camera = cams[i];
  73501. var cameraName = camera.name;
  73502. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73503. camera.detachPostProcess(postProcess);
  73504. });
  73505. if (this._cameras[cameraName]) {
  73506. //this._indicesForCamera.splice(index, 1);
  73507. this._cameras[cameraName] = null;
  73508. }
  73509. }
  73510. };
  73511. /**
  73512. * Enables the effect on given cameras
  73513. * @param cameras The camera to enable.
  73514. */
  73515. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73516. var _this = this;
  73517. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73518. if (!cams) {
  73519. return;
  73520. }
  73521. for (var i = 0; i < cams.length; i++) {
  73522. var camera = cams[i];
  73523. var cameraName = camera.name;
  73524. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73525. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73526. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73527. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73528. });
  73529. }
  73530. }
  73531. }
  73532. };
  73533. /**
  73534. * Disables the effect on the given cameras
  73535. * @param cameras The camera to disable.
  73536. */
  73537. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73538. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73539. if (!cams) {
  73540. return;
  73541. }
  73542. for (var i = 0; i < cams.length; i++) {
  73543. var camera = cams[i];
  73544. var cameraName = camera.name;
  73545. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73546. camera.detachPostProcess(postProcess);
  73547. });
  73548. }
  73549. };
  73550. /**
  73551. * Gets a list of the post processes contained in the effect.
  73552. * @param camera The camera to get the post processes on.
  73553. * @returns The list of the post processes in the effect.
  73554. */
  73555. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73556. if (this._singleInstance) {
  73557. return this._postProcesses[0];
  73558. }
  73559. else {
  73560. if (!camera) {
  73561. return null;
  73562. }
  73563. return this._postProcesses[camera.name];
  73564. }
  73565. };
  73566. return PostProcessRenderEffect;
  73567. }());
  73568. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73569. })(BABYLON || (BABYLON = {}));
  73570. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73571. var BABYLON;
  73572. (function (BABYLON) {
  73573. var PostProcessRenderPipeline = /** @class */ (function () {
  73574. function PostProcessRenderPipeline(engine, name) {
  73575. this.engine = engine;
  73576. this._name = name;
  73577. this._renderEffects = {};
  73578. this._renderEffectsForIsolatedPass = new Array();
  73579. this._cameras = [];
  73580. }
  73581. PostProcessRenderPipeline.prototype.getClassName = function () {
  73582. return "PostProcessRenderPipeline";
  73583. };
  73584. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73585. get: function () {
  73586. for (var renderEffectName in this._renderEffects) {
  73587. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73588. if (!this._renderEffects[renderEffectName].isSupported) {
  73589. return false;
  73590. }
  73591. }
  73592. }
  73593. return true;
  73594. },
  73595. enumerable: true,
  73596. configurable: true
  73597. });
  73598. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73599. this._renderEffects[renderEffect._name] = renderEffect;
  73600. };
  73601. // private
  73602. PostProcessRenderPipeline.prototype._rebuild = function () {
  73603. };
  73604. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73605. var renderEffects = this._renderEffects[renderEffectName];
  73606. if (!renderEffects) {
  73607. return;
  73608. }
  73609. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73610. };
  73611. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73612. var renderEffects = this._renderEffects[renderEffectName];
  73613. if (!renderEffects) {
  73614. return;
  73615. }
  73616. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73617. };
  73618. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73619. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73620. if (!cams) {
  73621. return;
  73622. }
  73623. var indicesToDelete = [];
  73624. var i;
  73625. for (i = 0; i < cams.length; i++) {
  73626. var camera = cams[i];
  73627. var cameraName = camera.name;
  73628. if (this._cameras.indexOf(camera) === -1) {
  73629. this._cameras[cameraName] = camera;
  73630. }
  73631. else if (unique) {
  73632. indicesToDelete.push(i);
  73633. }
  73634. }
  73635. for (i = 0; i < indicesToDelete.length; i++) {
  73636. cameras.splice(indicesToDelete[i], 1);
  73637. }
  73638. for (var renderEffectName in this._renderEffects) {
  73639. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73640. this._renderEffects[renderEffectName]._attachCameras(cams);
  73641. }
  73642. }
  73643. };
  73644. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73645. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73646. if (!cams) {
  73647. return;
  73648. }
  73649. for (var renderEffectName in this._renderEffects) {
  73650. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73651. this._renderEffects[renderEffectName]._detachCameras(cams);
  73652. }
  73653. }
  73654. for (var i = 0; i < cams.length; i++) {
  73655. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73656. }
  73657. };
  73658. PostProcessRenderPipeline.prototype._update = function () {
  73659. for (var renderEffectName in this._renderEffects) {
  73660. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73661. this._renderEffects[renderEffectName]._update();
  73662. }
  73663. }
  73664. for (var i = 0; i < this._cameras.length; i++) {
  73665. var cameraName = this._cameras[i].name;
  73666. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73667. this._renderEffectsForIsolatedPass[cameraName]._update();
  73668. }
  73669. }
  73670. };
  73671. PostProcessRenderPipeline.prototype._reset = function () {
  73672. this._renderEffects = {};
  73673. this._renderEffectsForIsolatedPass = new Array();
  73674. };
  73675. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73676. // 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)
  73677. var effectKeys = Object.keys(this._renderEffects);
  73678. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73679. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73680. if (postProcesses) {
  73681. postProcesses[0].samples = sampleCount;
  73682. return true;
  73683. }
  73684. }
  73685. return false;
  73686. };
  73687. PostProcessRenderPipeline.prototype.dispose = function () {
  73688. // Must be implemented by children
  73689. };
  73690. __decorate([
  73691. BABYLON.serialize()
  73692. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73693. return PostProcessRenderPipeline;
  73694. }());
  73695. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73696. })(BABYLON || (BABYLON = {}));
  73697. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73698. var BABYLON;
  73699. (function (BABYLON) {
  73700. /**
  73701. * This represents a depth renderer in Babylon.
  73702. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73703. */
  73704. var DepthRenderer = /** @class */ (function () {
  73705. /**
  73706. * Instantiates a depth renderer
  73707. * @param scene The scene the renderer belongs to
  73708. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73709. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73710. */
  73711. function DepthRenderer(scene, type, camera) {
  73712. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73713. if (camera === void 0) { camera = null; }
  73714. var _this = this;
  73715. this._scene = scene;
  73716. this._camera = camera;
  73717. var engine = scene.getEngine();
  73718. // Render target
  73719. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73720. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73721. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73722. this._depthMap.refreshRate = 1;
  73723. this._depthMap.renderParticles = false;
  73724. this._depthMap.renderList = null;
  73725. // Camera to get depth map from to support multiple concurrent cameras
  73726. this._depthMap.activeCamera = this._camera;
  73727. this._depthMap.ignoreCameraViewport = true;
  73728. this._depthMap.useCameraPostProcesses = false;
  73729. // set default depth value to 1.0 (far away)
  73730. this._depthMap.onClearObservable.add(function (engine) {
  73731. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73732. });
  73733. // Custom render function
  73734. var renderSubMesh = function (subMesh) {
  73735. var mesh = subMesh.getRenderingMesh();
  73736. var scene = _this._scene;
  73737. var engine = scene.getEngine();
  73738. var material = subMesh.getMaterial();
  73739. if (!material) {
  73740. return;
  73741. }
  73742. // Culling and reverse (right handed system)
  73743. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73744. // Managing instances
  73745. var batch = mesh._getInstancesRenderList(subMesh._id);
  73746. if (batch.mustReturn) {
  73747. return;
  73748. }
  73749. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73750. var camera = _this._camera || scene.activeCamera;
  73751. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73752. engine.enableEffect(_this._effect);
  73753. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73754. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73755. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73756. // Alpha test
  73757. if (material && material.needAlphaTesting()) {
  73758. var alphaTexture = material.getAlphaTestTexture();
  73759. if (alphaTexture) {
  73760. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73761. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73762. }
  73763. }
  73764. // Bones
  73765. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73766. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73767. }
  73768. // Draw
  73769. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73770. }
  73771. };
  73772. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73773. var index;
  73774. if (depthOnlySubMeshes.length) {
  73775. engine.setColorWrite(false);
  73776. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73777. renderSubMesh(depthOnlySubMeshes.data[index]);
  73778. }
  73779. engine.setColorWrite(true);
  73780. }
  73781. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73782. renderSubMesh(opaqueSubMeshes.data[index]);
  73783. }
  73784. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73785. renderSubMesh(alphaTestSubMeshes.data[index]);
  73786. }
  73787. };
  73788. }
  73789. /**
  73790. * Creates the depth rendering effect and checks if the effect is ready.
  73791. * @param subMesh The submesh to be used to render the depth map of
  73792. * @param useInstances If multiple world instances should be used
  73793. * @returns if the depth renderer is ready to render the depth map
  73794. */
  73795. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73796. var material = subMesh.getMaterial();
  73797. if (material.disableDepthWrite) {
  73798. return false;
  73799. }
  73800. var defines = [];
  73801. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73802. var mesh = subMesh.getMesh();
  73803. // Alpha test
  73804. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73805. defines.push("#define ALPHATEST");
  73806. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73807. attribs.push(BABYLON.VertexBuffer.UVKind);
  73808. defines.push("#define UV1");
  73809. }
  73810. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73811. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73812. defines.push("#define UV2");
  73813. }
  73814. }
  73815. // Bones
  73816. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73817. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73818. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73819. if (mesh.numBoneInfluencers > 4) {
  73820. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73821. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73822. }
  73823. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73824. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73825. }
  73826. else {
  73827. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73828. }
  73829. // Instances
  73830. if (useInstances) {
  73831. defines.push("#define INSTANCES");
  73832. attribs.push("world0");
  73833. attribs.push("world1");
  73834. attribs.push("world2");
  73835. attribs.push("world3");
  73836. }
  73837. // Get correct effect
  73838. var join = defines.join("\n");
  73839. if (this._cachedDefines !== join) {
  73840. this._cachedDefines = join;
  73841. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73842. }
  73843. return this._effect.isReady();
  73844. };
  73845. /**
  73846. * Gets the texture which the depth map will be written to.
  73847. * @returns The depth map texture
  73848. */
  73849. DepthRenderer.prototype.getDepthMap = function () {
  73850. return this._depthMap;
  73851. };
  73852. /**
  73853. * Disposes of the depth renderer.
  73854. */
  73855. DepthRenderer.prototype.dispose = function () {
  73856. this._depthMap.dispose();
  73857. };
  73858. return DepthRenderer;
  73859. }());
  73860. BABYLON.DepthRenderer = DepthRenderer;
  73861. })(BABYLON || (BABYLON = {}));
  73862. //# sourceMappingURL=babylon.depthRenderer.js.map
  73863. var BABYLON;
  73864. (function (BABYLON) {
  73865. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73866. __extends(SSAORenderingPipeline, _super);
  73867. /**
  73868. * @constructor
  73869. * @param {string} name - The rendering pipeline name
  73870. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73871. * @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 }
  73872. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73873. */
  73874. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73875. var _this = _super.call(this, scene.getEngine(), name) || this;
  73876. // Members
  73877. /**
  73878. * The PassPostProcess id in the pipeline that contains the original scene color
  73879. */
  73880. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73881. /**
  73882. * The SSAO PostProcess id in the pipeline
  73883. */
  73884. _this.SSAORenderEffect = "SSAORenderEffect";
  73885. /**
  73886. * The horizontal blur PostProcess id in the pipeline
  73887. */
  73888. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73889. /**
  73890. * The vertical blur PostProcess id in the pipeline
  73891. */
  73892. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73893. /**
  73894. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73895. */
  73896. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73897. /**
  73898. * The output strength of the SSAO post-process. Default value is 1.0.
  73899. */
  73900. _this.totalStrength = 1.0;
  73901. /**
  73902. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73903. */
  73904. _this.radius = 0.0001;
  73905. /**
  73906. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73907. * Must not be equal to fallOff and superior to fallOff.
  73908. * Default value is 0.975
  73909. */
  73910. _this.area = 0.0075;
  73911. /**
  73912. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73913. * Must not be equal to area and inferior to area.
  73914. * Default value is 0.0
  73915. */
  73916. _this.fallOff = 0.000001;
  73917. /**
  73918. * The base color of the SSAO post-process
  73919. * The final result is "base + ssao" between [0, 1]
  73920. */
  73921. _this.base = 0.5;
  73922. _this._firstUpdate = true;
  73923. _this._scene = scene;
  73924. // Set up assets
  73925. _this._createRandomTexture();
  73926. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73927. var ssaoRatio = ratio.ssaoRatio || ratio;
  73928. var combineRatio = ratio.combineRatio || ratio;
  73929. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73930. _this._createSSAOPostProcess(ssaoRatio);
  73931. _this._createBlurPostProcess(ssaoRatio);
  73932. _this._createSSAOCombinePostProcess(combineRatio);
  73933. // Set up pipeline
  73934. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73935. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73936. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73937. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73938. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73939. // Finish
  73940. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73941. if (cameras)
  73942. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73943. return _this;
  73944. }
  73945. // Public Methods
  73946. /**
  73947. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73948. */
  73949. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73950. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73951. for (var i = 0; i < this._scene.cameras.length; i++) {
  73952. var camera = this._scene.cameras[i];
  73953. this._originalColorPostProcess.dispose(camera);
  73954. this._ssaoPostProcess.dispose(camera);
  73955. this._blurHPostProcess.dispose(camera);
  73956. this._blurVPostProcess.dispose(camera);
  73957. this._ssaoCombinePostProcess.dispose(camera);
  73958. }
  73959. this._randomTexture.dispose();
  73960. if (disableDepthRender)
  73961. this._scene.disableDepthRenderer();
  73962. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73963. _super.prototype.dispose.call(this);
  73964. };
  73965. // Private Methods
  73966. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73967. var _this = this;
  73968. var size = 16;
  73969. 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);
  73970. 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);
  73971. this._blurHPostProcess.onActivateObservable.add(function () {
  73972. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73973. _this._blurHPostProcess.kernel = size * dw;
  73974. });
  73975. this._blurVPostProcess.onActivateObservable.add(function () {
  73976. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73977. _this._blurVPostProcess.kernel = size * dw;
  73978. });
  73979. };
  73980. SSAORenderingPipeline.prototype._rebuild = function () {
  73981. this._firstUpdate = true;
  73982. _super.prototype._rebuild.call(this);
  73983. };
  73984. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73985. var _this = this;
  73986. var numSamples = 16;
  73987. var sampleSphere = [
  73988. 0.5381, 0.1856, -0.4319,
  73989. 0.1379, 0.2486, 0.4430,
  73990. 0.3371, 0.5679, -0.0057,
  73991. -0.6999, -0.0451, -0.0019,
  73992. 0.0689, -0.1598, -0.8547,
  73993. 0.0560, 0.0069, -0.1843,
  73994. -0.0146, 0.1402, 0.0762,
  73995. 0.0100, -0.1924, -0.0344,
  73996. -0.3577, -0.5301, -0.4358,
  73997. -0.3169, 0.1063, 0.0158,
  73998. 0.0103, -0.5869, 0.0046,
  73999. -0.0897, -0.4940, 0.3287,
  74000. 0.7119, -0.0154, -0.0918,
  74001. -0.0533, 0.0596, -0.5411,
  74002. 0.0352, -0.0631, 0.5460,
  74003. -0.4776, 0.2847, -0.0271
  74004. ];
  74005. var samplesFactor = 1.0 / numSamples;
  74006. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  74007. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74008. "area", "fallOff", "base", "range", "viewport"
  74009. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74010. this._ssaoPostProcess.onApply = function (effect) {
  74011. if (_this._firstUpdate) {
  74012. effect.setArray3("sampleSphere", sampleSphere);
  74013. effect.setFloat("samplesFactor", samplesFactor);
  74014. effect.setFloat("randTextureTiles", 4.0);
  74015. }
  74016. effect.setFloat("totalStrength", _this.totalStrength);
  74017. effect.setFloat("radius", _this.radius);
  74018. effect.setFloat("area", _this.area);
  74019. effect.setFloat("fallOff", _this.fallOff);
  74020. effect.setFloat("base", _this.base);
  74021. effect.setTexture("textureSampler", _this._depthTexture);
  74022. effect.setTexture("randomSampler", _this._randomTexture);
  74023. };
  74024. };
  74025. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74026. var _this = this;
  74027. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74028. this._ssaoCombinePostProcess.onApply = function (effect) {
  74029. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  74030. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74031. };
  74032. };
  74033. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  74034. var size = 512;
  74035. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74036. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74037. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74038. var context = this._randomTexture.getContext();
  74039. var rand = function (min, max) {
  74040. return Math.random() * (max - min) + min;
  74041. };
  74042. var randVector = BABYLON.Vector3.Zero();
  74043. for (var x = 0; x < size; x++) {
  74044. for (var y = 0; y < size; y++) {
  74045. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  74046. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  74047. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  74048. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74049. context.fillRect(x, y, 1, 1);
  74050. }
  74051. }
  74052. this._randomTexture.update(false);
  74053. };
  74054. __decorate([
  74055. BABYLON.serialize()
  74056. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  74057. __decorate([
  74058. BABYLON.serialize()
  74059. ], SSAORenderingPipeline.prototype, "radius", void 0);
  74060. __decorate([
  74061. BABYLON.serialize()
  74062. ], SSAORenderingPipeline.prototype, "area", void 0);
  74063. __decorate([
  74064. BABYLON.serialize()
  74065. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  74066. __decorate([
  74067. BABYLON.serialize()
  74068. ], SSAORenderingPipeline.prototype, "base", void 0);
  74069. return SSAORenderingPipeline;
  74070. }(BABYLON.PostProcessRenderPipeline));
  74071. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  74072. })(BABYLON || (BABYLON = {}));
  74073. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  74074. var BABYLON;
  74075. (function (BABYLON) {
  74076. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  74077. __extends(SSAO2RenderingPipeline, _super);
  74078. /**
  74079. * @constructor
  74080. * @param {string} name - The rendering pipeline name
  74081. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74082. * @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 }
  74083. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74084. */
  74085. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  74086. var _this = _super.call(this, scene.getEngine(), name) || this;
  74087. // Members
  74088. /**
  74089. * The PassPostProcess id in the pipeline that contains the original scene color
  74090. */
  74091. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  74092. /**
  74093. * The SSAO PostProcess id in the pipeline
  74094. */
  74095. _this.SSAORenderEffect = "SSAORenderEffect";
  74096. /**
  74097. * The horizontal blur PostProcess id in the pipeline
  74098. */
  74099. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  74100. /**
  74101. * The vertical blur PostProcess id in the pipeline
  74102. */
  74103. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  74104. /**
  74105. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  74106. */
  74107. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  74108. /**
  74109. * The output strength of the SSAO post-process. Default value is 1.0.
  74110. */
  74111. _this.totalStrength = 1.0;
  74112. /**
  74113. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  74114. */
  74115. _this.maxZ = 100.0;
  74116. /**
  74117. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  74118. */
  74119. _this.minZAspect = 0.2;
  74120. /**
  74121. * Number of samples used for the SSAO calculations. Default value is 8
  74122. */
  74123. _this._samples = 8;
  74124. /**
  74125. * Are we using bilateral blur ?
  74126. */
  74127. _this._expensiveBlur = true;
  74128. /**
  74129. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  74130. */
  74131. _this.radius = 2.0;
  74132. /**
  74133. * The base color of the SSAO post-process
  74134. * The final result is "base + ssao" between [0, 1]
  74135. */
  74136. _this.base = 0.1;
  74137. _this._firstUpdate = true;
  74138. _this._scene = scene;
  74139. _this._ratio = ratio;
  74140. if (!_this.isSupported) {
  74141. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  74142. return _this;
  74143. }
  74144. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  74145. var blurRatio = _this._ratio.blurRatio || ratio;
  74146. // Set up assets
  74147. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  74148. _this._createRandomTexture();
  74149. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  74150. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  74151. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  74152. _this._createSSAOPostProcess(1.0);
  74153. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  74154. _this._createSSAOCombinePostProcess(blurRatio);
  74155. // Set up pipeline
  74156. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  74157. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  74158. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74159. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74160. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74161. // Finish
  74162. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74163. if (cameras)
  74164. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74165. return _this;
  74166. }
  74167. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  74168. get: function () {
  74169. return this._samples;
  74170. },
  74171. set: function (n) {
  74172. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  74173. this._samples = n;
  74174. this._sampleSphere = this._generateHemisphere();
  74175. this._firstUpdate = true;
  74176. },
  74177. enumerable: true,
  74178. configurable: true
  74179. });
  74180. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  74181. get: function () {
  74182. return this._expensiveBlur;
  74183. },
  74184. set: function (b) {
  74185. 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"]);
  74186. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  74187. this._expensiveBlur = b;
  74188. this._firstUpdate = true;
  74189. },
  74190. enumerable: true,
  74191. configurable: true
  74192. });
  74193. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  74194. /**
  74195. * Support test.
  74196. */
  74197. get: function () {
  74198. var engine = BABYLON.Engine.LastCreatedEngine;
  74199. if (!engine) {
  74200. return false;
  74201. }
  74202. return engine.getCaps().drawBuffersExtension;
  74203. },
  74204. enumerable: true,
  74205. configurable: true
  74206. });
  74207. // Public Methods
  74208. /**
  74209. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74210. */
  74211. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  74212. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  74213. for (var i = 0; i < this._scene.cameras.length; i++) {
  74214. var camera = this._scene.cameras[i];
  74215. this._originalColorPostProcess.dispose(camera);
  74216. this._ssaoPostProcess.dispose(camera);
  74217. this._blurHPostProcess.dispose(camera);
  74218. this._blurVPostProcess.dispose(camera);
  74219. this._ssaoCombinePostProcess.dispose(camera);
  74220. }
  74221. this._randomTexture.dispose();
  74222. if (disableGeometryBufferRenderer)
  74223. this._scene.disableGeometryBufferRenderer();
  74224. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74225. _super.prototype.dispose.call(this);
  74226. };
  74227. // Private Methods
  74228. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  74229. var _this = this;
  74230. this._samplerOffsets = [];
  74231. var expensive = this.expensiveBlur;
  74232. for (var i = -8; i < 8; i++) {
  74233. this._samplerOffsets.push(i * 2 + 0.5);
  74234. }
  74235. 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");
  74236. this._blurHPostProcess.onApply = function (effect) {
  74237. if (!_this._scene.activeCamera) {
  74238. return;
  74239. }
  74240. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  74241. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74242. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74243. effect.setFloat("radius", _this.radius);
  74244. effect.setTexture("depthSampler", _this._depthTexture);
  74245. if (_this._firstUpdate) {
  74246. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74247. }
  74248. };
  74249. 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");
  74250. this._blurVPostProcess.onApply = function (effect) {
  74251. if (!_this._scene.activeCamera) {
  74252. return;
  74253. }
  74254. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  74255. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74256. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74257. effect.setFloat("radius", _this.radius);
  74258. effect.setTexture("depthSampler", _this._depthTexture);
  74259. if (_this._firstUpdate) {
  74260. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74261. _this._firstUpdate = false;
  74262. }
  74263. };
  74264. };
  74265. SSAO2RenderingPipeline.prototype._rebuild = function () {
  74266. this._firstUpdate = true;
  74267. _super.prototype._rebuild.call(this);
  74268. };
  74269. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  74270. var numSamples = this.samples;
  74271. var result = [];
  74272. var vector, scale;
  74273. var rand = function (min, max) {
  74274. return Math.random() * (max - min) + min;
  74275. };
  74276. var i = 0;
  74277. while (i < numSamples) {
  74278. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  74279. vector.normalize();
  74280. scale = i / numSamples;
  74281. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  74282. vector.scaleInPlace(scale);
  74283. result.push(vector.x, vector.y, vector.z);
  74284. i++;
  74285. }
  74286. return result;
  74287. };
  74288. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74289. var _this = this;
  74290. var numSamples = this.samples;
  74291. this._sampleSphere = this._generateHemisphere();
  74292. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  74293. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74294. "base", "range", "projection", "near", "far", "texelSize",
  74295. "xViewport", "yViewport", "maxZ", "minZAspect"
  74296. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74297. this._ssaoPostProcess.onApply = function (effect) {
  74298. if (_this._firstUpdate) {
  74299. effect.setArray3("sampleSphere", _this._sampleSphere);
  74300. effect.setFloat("randTextureTiles", 4.0);
  74301. }
  74302. if (!_this._scene.activeCamera) {
  74303. return;
  74304. }
  74305. effect.setFloat("samplesFactor", 1 / _this.samples);
  74306. effect.setFloat("totalStrength", _this.totalStrength);
  74307. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  74308. effect.setFloat("radius", _this.radius);
  74309. effect.setFloat("maxZ", _this.maxZ);
  74310. effect.setFloat("minZAspect", _this.minZAspect);
  74311. effect.setFloat("base", _this.base);
  74312. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74313. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74314. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  74315. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74316. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74317. effect.setTexture("textureSampler", _this._depthTexture);
  74318. effect.setTexture("normalSampler", _this._normalTexture);
  74319. effect.setTexture("randomSampler", _this._randomTexture);
  74320. };
  74321. };
  74322. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74323. var _this = this;
  74324. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74325. this._ssaoCombinePostProcess.onApply = function (effect) {
  74326. var viewport = _this._scene.activeCamera.viewport;
  74327. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74328. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74329. };
  74330. };
  74331. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74332. var size = 512;
  74333. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74334. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74335. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74336. var context = this._randomTexture.getContext();
  74337. var rand = function (min, max) {
  74338. return Math.random() * (max - min) + min;
  74339. };
  74340. var randVector = BABYLON.Vector3.Zero();
  74341. for (var x = 0; x < size; x++) {
  74342. for (var y = 0; y < size; y++) {
  74343. randVector.x = rand(0.0, 1.0);
  74344. randVector.y = rand(0.0, 1.0);
  74345. randVector.z = 0.0;
  74346. randVector.normalize();
  74347. randVector.scaleInPlace(255);
  74348. randVector.x = Math.floor(randVector.x);
  74349. randVector.y = Math.floor(randVector.y);
  74350. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74351. context.fillRect(x, y, 1, 1);
  74352. }
  74353. }
  74354. this._randomTexture.update(false);
  74355. };
  74356. /**
  74357. * Serialize the rendering pipeline (Used when exporting)
  74358. * @returns the serialized object
  74359. */
  74360. SSAO2RenderingPipeline.prototype.serialize = function () {
  74361. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74362. serializationObject.customType = "SSAO2RenderingPipeline";
  74363. return serializationObject;
  74364. };
  74365. /**
  74366. * Parse the serialized pipeline
  74367. * @param source Source pipeline.
  74368. * @param scene The scene to load the pipeline to.
  74369. * @param rootUrl The URL of the serialized pipeline.
  74370. * @returns An instantiated pipeline from the serialized object.
  74371. */
  74372. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74373. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74374. };
  74375. __decorate([
  74376. BABYLON.serialize()
  74377. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74378. __decorate([
  74379. BABYLON.serialize()
  74380. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74381. __decorate([
  74382. BABYLON.serialize()
  74383. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74384. __decorate([
  74385. BABYLON.serialize("samples")
  74386. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74387. __decorate([
  74388. BABYLON.serialize()
  74389. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74390. __decorate([
  74391. BABYLON.serialize("expensiveBlur")
  74392. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74393. __decorate([
  74394. BABYLON.serialize()
  74395. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74396. __decorate([
  74397. BABYLON.serialize()
  74398. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74399. return SSAO2RenderingPipeline;
  74400. }(BABYLON.PostProcessRenderPipeline));
  74401. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74402. })(BABYLON || (BABYLON = {}));
  74403. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74404. // BABYLON.JS Chromatic Aberration GLSL Shader
  74405. // Author: Olivier Guyot
  74406. // Separates very slightly R, G and B colors on the edges of the screen
  74407. // Inspired by Francois Tarlier & Martins Upitis
  74408. var BABYLON;
  74409. (function (BABYLON) {
  74410. var LensRenderingPipeline = /** @class */ (function (_super) {
  74411. __extends(LensRenderingPipeline, _super);
  74412. /**
  74413. * @constructor
  74414. *
  74415. * Effect parameters are as follow:
  74416. * {
  74417. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74418. * edge_blur: number; // from 0 to x (1 for realism)
  74419. * distortion: number; // from 0 to x (1 for realism)
  74420. * grain_amount: number; // from 0 to 1
  74421. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74422. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74423. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74424. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74425. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74426. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74427. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74428. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74429. * }
  74430. * Note: if an effect parameter is unset, effect is disabled
  74431. *
  74432. * @param {string} name - The rendering pipeline name
  74433. * @param {object} parameters - An object containing all parameters (see above)
  74434. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74435. * @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)
  74436. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74437. */
  74438. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74439. if (ratio === void 0) { ratio = 1.0; }
  74440. var _this = _super.call(this, scene.getEngine(), name) || this;
  74441. // Lens effects can be of the following:
  74442. // - chromatic aberration (slight shift of RGB colors)
  74443. // - blur on the edge of the lens
  74444. // - lens distortion
  74445. // - depth-of-field blur & highlights enhancing
  74446. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74447. // - grain effect (noise or custom texture)
  74448. // Two additional texture samplers are needed:
  74449. // - depth map (for depth-of-field)
  74450. // - grain texture
  74451. /**
  74452. * The chromatic aberration PostProcess id in the pipeline
  74453. */
  74454. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74455. /**
  74456. * The highlights enhancing PostProcess id in the pipeline
  74457. */
  74458. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74459. /**
  74460. * The depth-of-field PostProcess id in the pipeline
  74461. */
  74462. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74463. _this._scene = scene;
  74464. // Fetch texture samplers
  74465. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74466. if (parameters.grain_texture) {
  74467. _this._grainTexture = parameters.grain_texture;
  74468. }
  74469. else {
  74470. _this._createGrainTexture();
  74471. }
  74472. // save parameters
  74473. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74474. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74475. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74476. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74477. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74478. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74479. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74480. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74481. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74482. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74483. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74484. // Create effects
  74485. _this._createChromaticAberrationPostProcess(ratio);
  74486. _this._createHighlightsPostProcess(ratio);
  74487. _this._createDepthOfFieldPostProcess(ratio / 4);
  74488. // Set up pipeline
  74489. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74490. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74491. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74492. if (_this._highlightsGain === -1) {
  74493. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74494. }
  74495. // Finish
  74496. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74497. if (cameras) {
  74498. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74499. }
  74500. return _this;
  74501. }
  74502. // public methods (self explanatory)
  74503. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74504. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74505. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74506. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74507. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74508. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74509. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74510. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74511. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74512. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74513. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74514. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74515. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74516. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74517. };
  74518. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74519. this._highlightsPostProcess.updateEffect();
  74520. };
  74521. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74522. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74523. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74524. this._highlightsGain = amount;
  74525. };
  74526. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74527. if (this._highlightsGain === -1) {
  74528. this._highlightsGain = 1.0;
  74529. }
  74530. this._highlightsThreshold = amount;
  74531. };
  74532. LensRenderingPipeline.prototype.disableHighlights = function () {
  74533. this._highlightsGain = -1;
  74534. };
  74535. /**
  74536. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74537. */
  74538. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74539. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74540. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74541. this._chromaticAberrationPostProcess = null;
  74542. this._highlightsPostProcess = null;
  74543. this._depthOfFieldPostProcess = null;
  74544. this._grainTexture.dispose();
  74545. if (disableDepthRender)
  74546. this._scene.disableDepthRenderer();
  74547. };
  74548. // colors shifting and distortion
  74549. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74550. var _this = this;
  74551. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74552. [], // samplers
  74553. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74554. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74555. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74556. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74557. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74558. effect.setFloat('radialIntensity', 1);
  74559. effect.setFloat2('direction', 17, 17);
  74560. effect.setFloat2('centerPosition', 0.5, 0.5);
  74561. };
  74562. };
  74563. // highlights enhancing
  74564. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74565. var _this = this;
  74566. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74567. [], // samplers
  74568. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74569. this._highlightsPostProcess.onApply = function (effect) {
  74570. effect.setFloat('gain', _this._highlightsGain);
  74571. effect.setFloat('threshold', _this._highlightsThreshold);
  74572. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74573. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74574. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74575. };
  74576. };
  74577. // colors shifting and distortion
  74578. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74579. var _this = this;
  74580. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74581. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74582. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74583. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74584. this._depthOfFieldPostProcess.onApply = function (effect) {
  74585. effect.setTexture("depthSampler", _this._depthTexture);
  74586. effect.setTexture("grainSampler", _this._grainTexture);
  74587. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74588. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74589. effect.setFloat('grain_amount', _this._grainAmount);
  74590. effect.setBool('blur_noise', _this._blurNoise);
  74591. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74592. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74593. effect.setFloat('distortion', _this._distortion);
  74594. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74595. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74596. effect.setFloat('aperture', _this._dofAperture);
  74597. effect.setFloat('darken', _this._dofDarken);
  74598. effect.setFloat('edge_blur', _this._edgeBlur);
  74599. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74600. if (_this._scene.activeCamera) {
  74601. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74602. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74603. }
  74604. };
  74605. };
  74606. // creates a black and white random noise texture, 512x512
  74607. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74608. var size = 512;
  74609. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74610. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74611. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74612. var context = this._grainTexture.getContext();
  74613. var rand = function (min, max) {
  74614. return Math.random() * (max - min) + min;
  74615. };
  74616. var value;
  74617. for (var x = 0; x < size; x++) {
  74618. for (var y = 0; y < size; y++) {
  74619. value = Math.floor(rand(0.42, 0.58) * 255);
  74620. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74621. context.fillRect(x, y, 1, 1);
  74622. }
  74623. }
  74624. this._grainTexture.update(false);
  74625. };
  74626. return LensRenderingPipeline;
  74627. }(BABYLON.PostProcessRenderPipeline));
  74628. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74629. })(BABYLON || (BABYLON = {}));
  74630. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74631. var BABYLON;
  74632. (function (BABYLON) {
  74633. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74634. __extends(StandardRenderingPipeline, _super);
  74635. /**
  74636. * @constructor
  74637. * @param {string} name - The rendering pipeline name
  74638. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74639. * @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)
  74640. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74641. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74642. */
  74643. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74644. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74645. var _this = _super.call(this, scene.getEngine(), name) || this;
  74646. _this.downSampleX4PostProcess = null;
  74647. _this.brightPassPostProcess = null;
  74648. _this.blurHPostProcesses = [];
  74649. _this.blurVPostProcesses = [];
  74650. _this.textureAdderPostProcess = null;
  74651. _this.volumetricLightPostProcess = null;
  74652. _this.volumetricLightSmoothXPostProcess = null;
  74653. _this.volumetricLightSmoothYPostProcess = null;
  74654. _this.volumetricLightMergePostProces = null;
  74655. _this.volumetricLightFinalPostProcess = null;
  74656. _this.luminancePostProcess = null;
  74657. _this.luminanceDownSamplePostProcesses = [];
  74658. _this.hdrPostProcess = null;
  74659. _this.textureAdderFinalPostProcess = null;
  74660. _this.lensFlareFinalPostProcess = null;
  74661. _this.hdrFinalPostProcess = null;
  74662. _this.lensFlarePostProcess = null;
  74663. _this.lensFlareComposePostProcess = null;
  74664. _this.motionBlurPostProcess = null;
  74665. _this.depthOfFieldPostProcess = null;
  74666. // Values
  74667. _this.brightThreshold = 1.0;
  74668. _this.blurWidth = 512.0;
  74669. _this.horizontalBlur = false;
  74670. _this.exposure = 1.0;
  74671. _this.lensTexture = null;
  74672. _this.volumetricLightCoefficient = 0.2;
  74673. _this.volumetricLightPower = 4.0;
  74674. _this.volumetricLightBlurScale = 64.0;
  74675. _this.sourceLight = null;
  74676. _this.hdrMinimumLuminance = 1.0;
  74677. _this.hdrDecreaseRate = 0.5;
  74678. _this.hdrIncreaseRate = 0.5;
  74679. _this.lensColorTexture = null;
  74680. _this.lensFlareStrength = 20.0;
  74681. _this.lensFlareGhostDispersal = 1.4;
  74682. _this.lensFlareHaloWidth = 0.7;
  74683. _this.lensFlareDistortionStrength = 16.0;
  74684. _this.lensStarTexture = null;
  74685. _this.lensFlareDirtTexture = null;
  74686. _this.depthOfFieldDistance = 10.0;
  74687. _this.depthOfFieldBlurWidth = 64.0;
  74688. _this.motionStrength = 1.0;
  74689. // IAnimatable
  74690. _this.animations = [];
  74691. _this._currentDepthOfFieldSource = null;
  74692. _this._hdrCurrentLuminance = 1.0;
  74693. // Getters and setters
  74694. _this._bloomEnabled = true;
  74695. _this._depthOfFieldEnabled = false;
  74696. _this._vlsEnabled = false;
  74697. _this._lensFlareEnabled = false;
  74698. _this._hdrEnabled = false;
  74699. _this._motionBlurEnabled = false;
  74700. _this._motionBlurSamples = 64.0;
  74701. _this._volumetricLightStepsCount = 50.0;
  74702. _this._cameras = cameras || [];
  74703. // Initialize
  74704. _this._scene = scene;
  74705. _this._basePostProcess = originalPostProcess;
  74706. _this._ratio = ratio;
  74707. // Misc
  74708. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74709. // Finish
  74710. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74711. _this._buildPipeline();
  74712. return _this;
  74713. }
  74714. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74715. get: function () {
  74716. return this._bloomEnabled;
  74717. },
  74718. set: function (enabled) {
  74719. if (this._bloomEnabled === enabled) {
  74720. return;
  74721. }
  74722. this._bloomEnabled = enabled;
  74723. this._buildPipeline();
  74724. },
  74725. enumerable: true,
  74726. configurable: true
  74727. });
  74728. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74729. get: function () {
  74730. return this._depthOfFieldEnabled;
  74731. },
  74732. set: function (enabled) {
  74733. if (this._depthOfFieldEnabled === enabled) {
  74734. return;
  74735. }
  74736. this._depthOfFieldEnabled = enabled;
  74737. this._buildPipeline();
  74738. },
  74739. enumerable: true,
  74740. configurable: true
  74741. });
  74742. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74743. get: function () {
  74744. return this._lensFlareEnabled;
  74745. },
  74746. set: function (enabled) {
  74747. if (this._lensFlareEnabled === enabled) {
  74748. return;
  74749. }
  74750. this._lensFlareEnabled = enabled;
  74751. this._buildPipeline();
  74752. },
  74753. enumerable: true,
  74754. configurable: true
  74755. });
  74756. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74757. get: function () {
  74758. return this._hdrEnabled;
  74759. },
  74760. set: function (enabled) {
  74761. if (this._hdrEnabled === enabled) {
  74762. return;
  74763. }
  74764. this._hdrEnabled = enabled;
  74765. this._buildPipeline();
  74766. },
  74767. enumerable: true,
  74768. configurable: true
  74769. });
  74770. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74771. get: function () {
  74772. return this._vlsEnabled;
  74773. },
  74774. set: function (enabled) {
  74775. if (this._vlsEnabled === enabled) {
  74776. return;
  74777. }
  74778. if (enabled) {
  74779. var geometry = this._scene.enableGeometryBufferRenderer();
  74780. if (!geometry) {
  74781. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74782. return;
  74783. }
  74784. }
  74785. this._vlsEnabled = enabled;
  74786. this._buildPipeline();
  74787. },
  74788. enumerable: true,
  74789. configurable: true
  74790. });
  74791. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74792. get: function () {
  74793. return this._motionBlurEnabled;
  74794. },
  74795. set: function (enabled) {
  74796. if (this._motionBlurEnabled === enabled) {
  74797. return;
  74798. }
  74799. this._motionBlurEnabled = enabled;
  74800. this._buildPipeline();
  74801. },
  74802. enumerable: true,
  74803. configurable: true
  74804. });
  74805. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74806. get: function () {
  74807. return this._volumetricLightStepsCount;
  74808. },
  74809. set: function (count) {
  74810. if (this.volumetricLightPostProcess) {
  74811. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74812. }
  74813. this._volumetricLightStepsCount = count;
  74814. },
  74815. enumerable: true,
  74816. configurable: true
  74817. });
  74818. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74819. get: function () {
  74820. return this._motionBlurSamples;
  74821. },
  74822. set: function (samples) {
  74823. if (this.motionBlurPostProcess) {
  74824. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74825. }
  74826. this._motionBlurSamples = samples;
  74827. },
  74828. enumerable: true,
  74829. configurable: true
  74830. });
  74831. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74832. var _this = this;
  74833. var ratio = this._ratio;
  74834. var scene = this._scene;
  74835. this._disposePostProcesses();
  74836. this._reset();
  74837. // Create pass post-process
  74838. if (!this._basePostProcess) {
  74839. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74840. this.originalPostProcess.onApply = function (effect) {
  74841. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74842. };
  74843. }
  74844. else {
  74845. this.originalPostProcess = this._basePostProcess;
  74846. }
  74847. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74848. this._currentDepthOfFieldSource = this.originalPostProcess;
  74849. if (this._bloomEnabled) {
  74850. // Create down sample X4 post-process
  74851. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74852. // Create bright pass post-process
  74853. this._createBrightPassPostProcess(scene, ratio / 2);
  74854. // Create gaussian blur post-processes (down sampling blurs)
  74855. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74856. // Create texture adder post-process
  74857. this._createTextureAdderPostProcess(scene, ratio);
  74858. // Create depth-of-field source post-process
  74859. 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);
  74860. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74861. }
  74862. if (this._vlsEnabled) {
  74863. // Create volumetric light
  74864. this._createVolumetricLightPostProcess(scene, ratio);
  74865. // Create volumetric light final post-process
  74866. 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);
  74867. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74868. }
  74869. if (this._lensFlareEnabled) {
  74870. // Create lens flare post-process
  74871. this._createLensFlarePostProcess(scene, ratio);
  74872. // Create depth-of-field source post-process post lens-flare and disable it now
  74873. 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);
  74874. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74875. }
  74876. if (this._hdrEnabled) {
  74877. // Create luminance
  74878. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74879. // Create HDR
  74880. this._createHdrPostProcess(scene, ratio);
  74881. // Create depth-of-field source post-process post hdr and disable it now
  74882. 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);
  74883. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74884. }
  74885. if (this._depthOfFieldEnabled) {
  74886. // Create gaussian blur used by depth-of-field
  74887. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74888. // Create depth-of-field post-process
  74889. this._createDepthOfFieldPostProcess(scene, ratio);
  74890. }
  74891. if (this._motionBlurEnabled) {
  74892. // Create motion blur post-process
  74893. this._createMotionBlurPostProcess(scene, ratio);
  74894. }
  74895. if (this._cameras !== null) {
  74896. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74897. }
  74898. };
  74899. // Down Sample X4 Post-Processs
  74900. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74901. var _this = this;
  74902. var downSampleX4Offsets = new Array(32);
  74903. 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);
  74904. this.downSampleX4PostProcess.onApply = function (effect) {
  74905. var id = 0;
  74906. var width = _this.downSampleX4PostProcess.width;
  74907. var height = _this.downSampleX4PostProcess.height;
  74908. for (var i = -2; i < 2; i++) {
  74909. for (var j = -2; j < 2; j++) {
  74910. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74911. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74912. id += 2;
  74913. }
  74914. }
  74915. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74916. };
  74917. // Add to pipeline
  74918. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74919. };
  74920. // Brightpass Post-Process
  74921. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74922. var _this = this;
  74923. var brightOffsets = new Array(8);
  74924. 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);
  74925. this.brightPassPostProcess.onApply = function (effect) {
  74926. var sU = (1.0 / _this.brightPassPostProcess.width);
  74927. var sV = (1.0 / _this.brightPassPostProcess.height);
  74928. brightOffsets[0] = -0.5 * sU;
  74929. brightOffsets[1] = 0.5 * sV;
  74930. brightOffsets[2] = 0.5 * sU;
  74931. brightOffsets[3] = 0.5 * sV;
  74932. brightOffsets[4] = -0.5 * sU;
  74933. brightOffsets[5] = -0.5 * sV;
  74934. brightOffsets[6] = 0.5 * sU;
  74935. brightOffsets[7] = -0.5 * sV;
  74936. effect.setArray2("dsOffsets", brightOffsets);
  74937. effect.setFloat("brightThreshold", _this.brightThreshold);
  74938. };
  74939. // Add to pipeline
  74940. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74941. };
  74942. // Create blur H&V post-processes
  74943. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74944. var _this = this;
  74945. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74946. var engine = scene.getEngine();
  74947. 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);
  74948. 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);
  74949. blurX.onActivateObservable.add(function () {
  74950. var dw = blurX.width / engine.getRenderWidth();
  74951. blurX.kernel = _this[blurWidthKey] * dw;
  74952. });
  74953. blurY.onActivateObservable.add(function () {
  74954. var dw = blurY.height / engine.getRenderHeight();
  74955. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74956. });
  74957. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74958. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74959. this.blurHPostProcesses.push(blurX);
  74960. this.blurVPostProcesses.push(blurY);
  74961. };
  74962. // Create texture adder post-process
  74963. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74964. var _this = this;
  74965. 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);
  74966. this.textureAdderPostProcess.onApply = function (effect) {
  74967. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74968. effect.setTexture("lensSampler", _this.lensTexture);
  74969. effect.setFloat("exposure", _this.exposure);
  74970. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74971. };
  74972. // Add to pipeline
  74973. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74974. };
  74975. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74976. var _this = this;
  74977. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74978. geometryRenderer.enablePosition = true;
  74979. var geometry = geometryRenderer.getGBuffer();
  74980. // Base post-process
  74981. 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));
  74982. var depthValues = BABYLON.Vector2.Zero();
  74983. this.volumetricLightPostProcess.onApply = function (effect) {
  74984. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74985. var generator = _this.sourceLight.getShadowGenerator();
  74986. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74987. effect.setTexture("positionSampler", geometry.textures[2]);
  74988. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74989. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74990. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74991. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74992. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74993. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74994. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74995. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74996. effect.setVector2("depthValues", depthValues);
  74997. }
  74998. };
  74999. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  75000. // Smooth
  75001. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  75002. // Merge
  75003. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  75004. this.volumetricLightMergePostProces.onApply = function (effect) {
  75005. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  75006. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  75007. };
  75008. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  75009. };
  75010. // Create luminance
  75011. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  75012. var _this = this;
  75013. // Create luminance
  75014. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  75015. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  75016. var offsets = [];
  75017. this.luminancePostProcess.onApply = function (effect) {
  75018. var sU = (1.0 / _this.luminancePostProcess.width);
  75019. var sV = (1.0 / _this.luminancePostProcess.height);
  75020. offsets[0] = -0.5 * sU;
  75021. offsets[1] = 0.5 * sV;
  75022. offsets[2] = 0.5 * sU;
  75023. offsets[3] = 0.5 * sV;
  75024. offsets[4] = -0.5 * sU;
  75025. offsets[5] = -0.5 * sV;
  75026. offsets[6] = 0.5 * sU;
  75027. offsets[7] = -0.5 * sV;
  75028. effect.setArray2("lumOffsets", offsets);
  75029. };
  75030. // Add to pipeline
  75031. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  75032. // Create down sample luminance
  75033. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  75034. var size = Math.pow(3, i);
  75035. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  75036. if (i === 0) {
  75037. defines += "#define FINAL_DOWN_SAMPLER";
  75038. }
  75039. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  75040. this.luminanceDownSamplePostProcesses.push(postProcess);
  75041. }
  75042. // Create callbacks and add effects
  75043. var lastLuminance = this.luminancePostProcess;
  75044. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  75045. var downSampleOffsets = new Array(18);
  75046. pp.onApply = function (effect) {
  75047. if (!lastLuminance) {
  75048. return;
  75049. }
  75050. var id = 0;
  75051. for (var x = -1; x < 2; x++) {
  75052. for (var y = -1; y < 2; y++) {
  75053. downSampleOffsets[id] = x / lastLuminance.width;
  75054. downSampleOffsets[id + 1] = y / lastLuminance.height;
  75055. id += 2;
  75056. }
  75057. }
  75058. effect.setArray2("dsOffsets", downSampleOffsets);
  75059. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  75060. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  75061. lastLuminance = _this.luminancePostProcess;
  75062. }
  75063. else {
  75064. lastLuminance = pp;
  75065. }
  75066. };
  75067. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  75068. pp.onAfterRender = function (effect) {
  75069. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  75070. 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);
  75071. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  75072. };
  75073. }
  75074. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  75075. });
  75076. };
  75077. // Create HDR post-process
  75078. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  75079. var _this = this;
  75080. 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);
  75081. var outputLiminance = 1;
  75082. var time = 0;
  75083. var lastTime = 0;
  75084. this.hdrPostProcess.onApply = function (effect) {
  75085. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  75086. time += scene.getEngine().getDeltaTime();
  75087. if (outputLiminance < 0) {
  75088. outputLiminance = _this._hdrCurrentLuminance;
  75089. }
  75090. else {
  75091. var dt = (lastTime - time) / 1000.0;
  75092. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  75093. outputLiminance += _this.hdrDecreaseRate * dt;
  75094. }
  75095. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  75096. outputLiminance -= _this.hdrIncreaseRate * dt;
  75097. }
  75098. else {
  75099. outputLiminance = _this._hdrCurrentLuminance;
  75100. }
  75101. }
  75102. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  75103. effect.setFloat("averageLuminance", outputLiminance);
  75104. lastTime = time;
  75105. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  75106. };
  75107. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  75108. };
  75109. // Create lens flare post-process
  75110. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  75111. var _this = this;
  75112. 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);
  75113. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  75114. this._createBlurPostProcesses(scene, ratio / 4, 2);
  75115. 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);
  75116. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  75117. var resolution = new BABYLON.Vector2(0, 0);
  75118. // Lens flare
  75119. this.lensFlarePostProcess.onApply = function (effect) {
  75120. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  75121. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  75122. effect.setFloat("strength", _this.lensFlareStrength);
  75123. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  75124. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  75125. // Shift
  75126. resolution.x = _this.lensFlarePostProcess.width;
  75127. resolution.y = _this.lensFlarePostProcess.height;
  75128. effect.setVector2("resolution", resolution);
  75129. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  75130. };
  75131. // Compose
  75132. 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);
  75133. 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);
  75134. this.lensFlareComposePostProcess.onApply = function (effect) {
  75135. if (!_this._scene.activeCamera) {
  75136. return;
  75137. }
  75138. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75139. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  75140. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  75141. // Lens start rotation matrix
  75142. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  75143. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  75144. 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));
  75145. camRot *= 4.0;
  75146. 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);
  75147. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  75148. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  75149. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  75150. };
  75151. };
  75152. // Create depth-of-field post-process
  75153. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  75154. var _this = this;
  75155. 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);
  75156. this.depthOfFieldPostProcess.onApply = function (effect) {
  75157. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75158. effect.setTexture("depthSampler", _this._getDepthTexture());
  75159. effect.setFloat("distance", _this.depthOfFieldDistance);
  75160. };
  75161. // Add to pipeline
  75162. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  75163. };
  75164. // Create motion blur post-process
  75165. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  75166. var _this = this;
  75167. 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);
  75168. var motionScale = 0;
  75169. var prevViewProjection = BABYLON.Matrix.Identity();
  75170. var invViewProjection = BABYLON.Matrix.Identity();
  75171. var viewProjection = BABYLON.Matrix.Identity();
  75172. var screenSize = BABYLON.Vector2.Zero();
  75173. this.motionBlurPostProcess.onApply = function (effect) {
  75174. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  75175. viewProjection.invertToRef(invViewProjection);
  75176. effect.setMatrix("inverseViewProjection", invViewProjection);
  75177. effect.setMatrix("prevViewProjection", prevViewProjection);
  75178. prevViewProjection = viewProjection;
  75179. screenSize.x = _this.motionBlurPostProcess.width;
  75180. screenSize.y = _this.motionBlurPostProcess.height;
  75181. effect.setVector2("screenSize", screenSize);
  75182. motionScale = scene.getEngine().getFps() / 60.0;
  75183. effect.setFloat("motionScale", motionScale);
  75184. effect.setFloat("motionStrength", _this.motionStrength);
  75185. effect.setTexture("depthSampler", _this._getDepthTexture());
  75186. };
  75187. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  75188. };
  75189. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  75190. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  75191. var renderer = this._scene.enableGeometryBufferRenderer();
  75192. return renderer.getGBuffer().textures[0];
  75193. }
  75194. return this._scene.enableDepthRenderer().getDepthMap();
  75195. };
  75196. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  75197. for (var i = 0; i < this._cameras.length; i++) {
  75198. var camera = this._cameras[i];
  75199. if (this.originalPostProcess) {
  75200. this.originalPostProcess.dispose(camera);
  75201. }
  75202. if (this.downSampleX4PostProcess) {
  75203. this.downSampleX4PostProcess.dispose(camera);
  75204. }
  75205. if (this.brightPassPostProcess) {
  75206. this.brightPassPostProcess.dispose(camera);
  75207. }
  75208. if (this.textureAdderPostProcess) {
  75209. this.textureAdderPostProcess.dispose(camera);
  75210. }
  75211. if (this.textureAdderFinalPostProcess) {
  75212. this.textureAdderFinalPostProcess.dispose(camera);
  75213. }
  75214. if (this.volumetricLightPostProcess) {
  75215. this.volumetricLightPostProcess.dispose(camera);
  75216. }
  75217. if (this.volumetricLightSmoothXPostProcess) {
  75218. this.volumetricLightSmoothXPostProcess.dispose(camera);
  75219. }
  75220. if (this.volumetricLightSmoothYPostProcess) {
  75221. this.volumetricLightSmoothYPostProcess.dispose(camera);
  75222. }
  75223. if (this.volumetricLightMergePostProces) {
  75224. this.volumetricLightMergePostProces.dispose(camera);
  75225. }
  75226. if (this.volumetricLightFinalPostProcess) {
  75227. this.volumetricLightFinalPostProcess.dispose(camera);
  75228. }
  75229. if (this.lensFlarePostProcess) {
  75230. this.lensFlarePostProcess.dispose(camera);
  75231. }
  75232. if (this.lensFlareComposePostProcess) {
  75233. this.lensFlareComposePostProcess.dispose(camera);
  75234. }
  75235. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  75236. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  75237. }
  75238. if (this.luminancePostProcess) {
  75239. this.luminancePostProcess.dispose(camera);
  75240. }
  75241. if (this.hdrPostProcess) {
  75242. this.hdrPostProcess.dispose(camera);
  75243. }
  75244. if (this.hdrFinalPostProcess) {
  75245. this.hdrFinalPostProcess.dispose(camera);
  75246. }
  75247. if (this.depthOfFieldPostProcess) {
  75248. this.depthOfFieldPostProcess.dispose(camera);
  75249. }
  75250. if (this.motionBlurPostProcess) {
  75251. this.motionBlurPostProcess.dispose(camera);
  75252. }
  75253. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  75254. this.blurHPostProcesses[j].dispose(camera);
  75255. }
  75256. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  75257. this.blurVPostProcesses[j].dispose(camera);
  75258. }
  75259. }
  75260. this.originalPostProcess = null;
  75261. this.downSampleX4PostProcess = null;
  75262. this.brightPassPostProcess = null;
  75263. this.textureAdderPostProcess = null;
  75264. this.textureAdderFinalPostProcess = null;
  75265. this.volumetricLightPostProcess = null;
  75266. this.volumetricLightSmoothXPostProcess = null;
  75267. this.volumetricLightSmoothYPostProcess = null;
  75268. this.volumetricLightMergePostProces = null;
  75269. this.volumetricLightFinalPostProcess = null;
  75270. this.lensFlarePostProcess = null;
  75271. this.lensFlareComposePostProcess = null;
  75272. this.luminancePostProcess = null;
  75273. this.hdrPostProcess = null;
  75274. this.hdrFinalPostProcess = null;
  75275. this.depthOfFieldPostProcess = null;
  75276. this.motionBlurPostProcess = null;
  75277. this.luminanceDownSamplePostProcesses = [];
  75278. this.blurHPostProcesses = [];
  75279. this.blurVPostProcesses = [];
  75280. };
  75281. /**
  75282. * Dispose of the pipeline and stop all post processes
  75283. */
  75284. StandardRenderingPipeline.prototype.dispose = function () {
  75285. this._disposePostProcesses();
  75286. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75287. _super.prototype.dispose.call(this);
  75288. };
  75289. /**
  75290. * Serialize the rendering pipeline (Used when exporting)
  75291. * @returns the serialized object
  75292. */
  75293. StandardRenderingPipeline.prototype.serialize = function () {
  75294. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75295. if (this.sourceLight) {
  75296. serializationObject.sourceLightId = this.sourceLight.id;
  75297. }
  75298. serializationObject.customType = "StandardRenderingPipeline";
  75299. return serializationObject;
  75300. };
  75301. /**
  75302. * Parse the serialized pipeline
  75303. * @param source Source pipeline.
  75304. * @param scene The scene to load the pipeline to.
  75305. * @param rootUrl The URL of the serialized pipeline.
  75306. * @returns An instantiated pipeline from the serialized object.
  75307. */
  75308. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75309. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75310. if (source.sourceLightId) {
  75311. p.sourceLight = scene.getLightByID(source.sourceLightId);
  75312. }
  75313. return p;
  75314. };
  75315. // Luminance steps
  75316. StandardRenderingPipeline.LuminanceSteps = 6;
  75317. __decorate([
  75318. BABYLON.serialize()
  75319. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75320. __decorate([
  75321. BABYLON.serialize()
  75322. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75323. __decorate([
  75324. BABYLON.serialize()
  75325. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75326. __decorate([
  75327. BABYLON.serialize()
  75328. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75329. __decorate([
  75330. BABYLON.serializeAsTexture("lensTexture")
  75331. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75332. __decorate([
  75333. BABYLON.serialize()
  75334. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75335. __decorate([
  75336. BABYLON.serialize()
  75337. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75338. __decorate([
  75339. BABYLON.serialize()
  75340. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75341. __decorate([
  75342. BABYLON.serialize()
  75343. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75344. __decorate([
  75345. BABYLON.serialize()
  75346. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75347. __decorate([
  75348. BABYLON.serialize()
  75349. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75350. __decorate([
  75351. BABYLON.serializeAsTexture("lensColorTexture")
  75352. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75353. __decorate([
  75354. BABYLON.serialize()
  75355. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75356. __decorate([
  75357. BABYLON.serialize()
  75358. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75359. __decorate([
  75360. BABYLON.serialize()
  75361. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75362. __decorate([
  75363. BABYLON.serialize()
  75364. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75365. __decorate([
  75366. BABYLON.serializeAsTexture("lensStarTexture")
  75367. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75368. __decorate([
  75369. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75370. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75371. __decorate([
  75372. BABYLON.serialize()
  75373. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75374. __decorate([
  75375. BABYLON.serialize()
  75376. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75377. __decorate([
  75378. BABYLON.serialize()
  75379. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75380. __decorate([
  75381. BABYLON.serialize()
  75382. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75383. __decorate([
  75384. BABYLON.serialize()
  75385. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75386. __decorate([
  75387. BABYLON.serialize()
  75388. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75389. __decorate([
  75390. BABYLON.serialize()
  75391. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75392. __decorate([
  75393. BABYLON.serialize()
  75394. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75395. __decorate([
  75396. BABYLON.serialize()
  75397. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75398. __decorate([
  75399. BABYLON.serialize()
  75400. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75401. __decorate([
  75402. BABYLON.serialize()
  75403. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75404. __decorate([
  75405. BABYLON.serialize()
  75406. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75407. return StandardRenderingPipeline;
  75408. }(BABYLON.PostProcessRenderPipeline));
  75409. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75410. })(BABYLON || (BABYLON = {}));
  75411. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75412. var BABYLON;
  75413. (function (BABYLON) {
  75414. var FxaaPostProcess = /** @class */ (function (_super) {
  75415. __extends(FxaaPostProcess, _super);
  75416. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75417. if (camera === void 0) { camera = null; }
  75418. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75419. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75420. var defines = _this._getDefines();
  75421. _this.updateEffect(defines);
  75422. _this.onApplyObservable.add(function (effect) {
  75423. var texelSize = _this.texelSize;
  75424. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75425. });
  75426. return _this;
  75427. }
  75428. FxaaPostProcess.prototype._getDefines = function () {
  75429. var engine = this.getEngine();
  75430. if (!engine) {
  75431. return null;
  75432. }
  75433. var glInfo = engine.getGlInfo();
  75434. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75435. return "#define MALI 1\n";
  75436. }
  75437. return null;
  75438. };
  75439. return FxaaPostProcess;
  75440. }(BABYLON.PostProcess));
  75441. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75442. })(BABYLON || (BABYLON = {}));
  75443. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75444. var BABYLON;
  75445. (function (BABYLON) {
  75446. /**
  75447. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75448. */
  75449. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75450. __extends(ChromaticAberrationPostProcess, _super);
  75451. /**
  75452. * Creates a new instance ChromaticAberrationPostProcess
  75453. * @param name The name of the effect.
  75454. * @param screenWidth The width of the screen to apply the effect on.
  75455. * @param screenHeight The height of the screen to apply the effect on.
  75456. * @param options The required width/height ratio to downsize to before computing the render pass.
  75457. * @param camera The camera to apply the render pass to.
  75458. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75459. * @param engine The engine which the post process will be applied. (default: current engine)
  75460. * @param reusable If the post process can be reused on the same frame. (default: false)
  75461. * @param textureType Type of textures used when performing the post process. (default: 0)
  75462. * @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)
  75463. */
  75464. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75465. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75466. if (blockCompilation === void 0) { blockCompilation = false; }
  75467. 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;
  75468. /**
  75469. * The amount of seperation of rgb channels (default: 30)
  75470. */
  75471. _this.aberrationAmount = 30;
  75472. /**
  75473. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75474. */
  75475. _this.radialIntensity = 0;
  75476. /**
  75477. * 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))
  75478. */
  75479. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75480. /**
  75481. * 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))
  75482. */
  75483. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75484. _this.onApplyObservable.add(function (effect) {
  75485. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75486. effect.setFloat('screen_width', screenWidth);
  75487. effect.setFloat('screen_height', screenHeight);
  75488. effect.setFloat('radialIntensity', _this.radialIntensity);
  75489. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75490. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75491. });
  75492. return _this;
  75493. }
  75494. return ChromaticAberrationPostProcess;
  75495. }(BABYLON.PostProcess));
  75496. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75497. })(BABYLON || (BABYLON = {}));
  75498. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75499. var BABYLON;
  75500. (function (BABYLON) {
  75501. /**
  75502. * The GrainPostProcess adds noise to the image at mid luminance levels
  75503. */
  75504. var GrainPostProcess = /** @class */ (function (_super) {
  75505. __extends(GrainPostProcess, _super);
  75506. /**
  75507. * Creates a new instance of @see GrainPostProcess
  75508. * @param name The name of the effect.
  75509. * @param options The required width/height ratio to downsize to before computing the render pass.
  75510. * @param camera The camera to apply the render pass to.
  75511. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75512. * @param engine The engine which the post process will be applied. (default: current engine)
  75513. * @param reusable If the post process can be reused on the same frame. (default: false)
  75514. * @param textureType Type of textures used when performing the post process. (default: 0)
  75515. * @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)
  75516. */
  75517. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75518. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75519. if (blockCompilation === void 0) { blockCompilation = false; }
  75520. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75521. /**
  75522. * The intensity of the grain added (default: 30)
  75523. */
  75524. _this.intensity = 30;
  75525. /**
  75526. * If the grain should be randomized on every frame
  75527. */
  75528. _this.animated = false;
  75529. _this.onApplyObservable.add(function (effect) {
  75530. effect.setFloat('intensity', _this.intensity);
  75531. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75532. });
  75533. return _this;
  75534. }
  75535. return GrainPostProcess;
  75536. }(BABYLON.PostProcess));
  75537. BABYLON.GrainPostProcess = GrainPostProcess;
  75538. })(BABYLON || (BABYLON = {}));
  75539. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75540. var BABYLON;
  75541. (function (BABYLON) {
  75542. /**
  75543. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75544. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75545. */
  75546. var SharpenPostProcess = /** @class */ (function (_super) {
  75547. __extends(SharpenPostProcess, _super);
  75548. /**
  75549. * Creates a new instance ConvolutionPostProcess
  75550. * @param name The name of the effect.
  75551. * @param options The required width/height ratio to downsize to before computing the render pass.
  75552. * @param camera The camera to apply the render pass to.
  75553. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75554. * @param engine The engine which the post process will be applied. (default: current engine)
  75555. * @param reusable If the post process can be reused on the same frame. (default: false)
  75556. * @param textureType Type of textures used when performing the post process. (default: 0)
  75557. * @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)
  75558. */
  75559. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75560. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75561. if (blockCompilation === void 0) { blockCompilation = false; }
  75562. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75563. /**
  75564. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75565. */
  75566. _this.colorAmount = 1.0;
  75567. /**
  75568. * How much sharpness should be applied (default: 0.3)
  75569. */
  75570. _this.edgeAmount = 0.3;
  75571. _this.onApply = function (effect) {
  75572. effect.setFloat2("screenSize", _this.width, _this.height);
  75573. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75574. };
  75575. return _this;
  75576. }
  75577. return SharpenPostProcess;
  75578. }(BABYLON.PostProcess));
  75579. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75580. })(BABYLON || (BABYLON = {}));
  75581. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75582. var BABYLON;
  75583. (function (BABYLON) {
  75584. /**
  75585. * The Blur Post Process which blurs an image based on a kernel and direction.
  75586. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75587. */
  75588. var BlurPostProcess = /** @class */ (function (_super) {
  75589. __extends(BlurPostProcess, _super);
  75590. /**
  75591. * Creates a new instance BlurPostProcess
  75592. * @param name The name of the effect.
  75593. * @param direction The direction in which to blur the image.
  75594. * @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.
  75595. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75596. * @param camera The camera to apply the render pass to.
  75597. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75598. * @param engine The engine which the post process will be applied. (default: current engine)
  75599. * @param reusable If the post process can be reused on the same frame. (default: false)
  75600. * @param textureType Type of textures used when performing the post process. (default: 0)
  75601. * @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)
  75602. */
  75603. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75604. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75605. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75606. if (defines === void 0) { defines = ""; }
  75607. if (blockCompilation === void 0) { blockCompilation = false; }
  75608. 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;
  75609. _this.direction = direction;
  75610. _this.blockCompilation = blockCompilation;
  75611. _this._packedFloat = false;
  75612. _this._staticDefines = "";
  75613. _this._staticDefines = defines;
  75614. _this.onApplyObservable.add(function (effect) {
  75615. if (_this._outputTexture) {
  75616. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75617. }
  75618. else {
  75619. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75620. }
  75621. });
  75622. _this.kernel = kernel;
  75623. return _this;
  75624. }
  75625. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75626. /**
  75627. * Gets the length in pixels of the blur sample region
  75628. */
  75629. get: function () {
  75630. return this._idealKernel;
  75631. },
  75632. /**
  75633. * Sets the length in pixels of the blur sample region
  75634. */
  75635. set: function (v) {
  75636. if (this._idealKernel === v) {
  75637. return;
  75638. }
  75639. v = Math.max(v, 1);
  75640. this._idealKernel = v;
  75641. this._kernel = this._nearestBestKernel(v);
  75642. if (!this.blockCompilation) {
  75643. this._updateParameters();
  75644. }
  75645. },
  75646. enumerable: true,
  75647. configurable: true
  75648. });
  75649. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75650. /**
  75651. * Gets wether or not the blur is unpacking/repacking floats
  75652. */
  75653. get: function () {
  75654. return this._packedFloat;
  75655. },
  75656. /**
  75657. * Sets wether or not the blur needs to unpack/repack floats
  75658. */
  75659. set: function (v) {
  75660. if (this._packedFloat === v) {
  75661. return;
  75662. }
  75663. this._packedFloat = v;
  75664. if (!this.blockCompilation) {
  75665. this._updateParameters();
  75666. }
  75667. },
  75668. enumerable: true,
  75669. configurable: true
  75670. });
  75671. /**
  75672. * Updates the effect with the current post process compile time values and recompiles the shader.
  75673. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75674. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75675. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75676. * @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
  75677. * @param onCompiled Called when the shader has been compiled.
  75678. * @param onError Called if there is an error when compiling a shader.
  75679. */
  75680. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75681. if (defines === void 0) { defines = null; }
  75682. if (uniforms === void 0) { uniforms = null; }
  75683. if (samplers === void 0) { samplers = null; }
  75684. this._updateParameters(onCompiled, onError);
  75685. };
  75686. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75687. // Generate sampling offsets and weights
  75688. var N = this._kernel;
  75689. var centerIndex = (N - 1) / 2;
  75690. // Generate Gaussian sampling weights over kernel
  75691. var offsets = [];
  75692. var weights = [];
  75693. var totalWeight = 0;
  75694. for (var i = 0; i < N; i++) {
  75695. var u = i / (N - 1);
  75696. var w = this._gaussianWeight(u * 2.0 - 1);
  75697. offsets[i] = (i - centerIndex);
  75698. weights[i] = w;
  75699. totalWeight += w;
  75700. }
  75701. // Normalize weights
  75702. for (var i = 0; i < weights.length; i++) {
  75703. weights[i] /= totalWeight;
  75704. }
  75705. // Optimize: combine samples to take advantage of hardware linear sampling
  75706. // Walk from left to center, combining pairs (symmetrically)
  75707. var linearSamplingWeights = [];
  75708. var linearSamplingOffsets = [];
  75709. var linearSamplingMap = [];
  75710. for (var i = 0; i <= centerIndex; i += 2) {
  75711. var j = Math.min(i + 1, Math.floor(centerIndex));
  75712. var singleCenterSample = i === j;
  75713. if (singleCenterSample) {
  75714. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75715. }
  75716. else {
  75717. var sharedCell = j === centerIndex;
  75718. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75719. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75720. if (offsetLinear === 0) {
  75721. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75722. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75723. }
  75724. else {
  75725. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75726. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75727. }
  75728. }
  75729. }
  75730. for (var i = 0; i < linearSamplingMap.length; i++) {
  75731. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75732. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75733. }
  75734. // Replace with optimized
  75735. offsets = linearSamplingOffsets;
  75736. weights = linearSamplingWeights;
  75737. // Generate shaders
  75738. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75739. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75740. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75741. var defines = "";
  75742. defines += this._staticDefines;
  75743. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75744. if (this._staticDefines.indexOf("DOF") != -1) {
  75745. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75746. varyingCount--;
  75747. }
  75748. for (var i = 0; i < varyingCount; i++) {
  75749. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75750. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75751. }
  75752. var depCount = 0;
  75753. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75754. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75755. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75756. depCount++;
  75757. }
  75758. if (this.packedFloat) {
  75759. defines += "#define PACKEDFLOAT 1";
  75760. }
  75761. this.blockCompilation = false;
  75762. _super.prototype.updateEffect.call(this, defines, null, null, {
  75763. varyingCount: varyingCount,
  75764. depCount: depCount
  75765. }, onCompiled, onError);
  75766. };
  75767. /**
  75768. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75769. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75770. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75771. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75772. * The gaps between physical kernels are compensated for in the weighting of the samples
  75773. * @param idealKernel Ideal blur kernel.
  75774. * @return Nearest best kernel.
  75775. */
  75776. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75777. var v = Math.round(idealKernel);
  75778. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75779. var k = _a[_i];
  75780. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75781. return Math.max(k, 3);
  75782. }
  75783. }
  75784. return Math.max(v, 3);
  75785. };
  75786. /**
  75787. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75788. * @param x The point on the Gaussian distribution to sample.
  75789. * @return the value of the Gaussian function at x.
  75790. */
  75791. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75792. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75793. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75794. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75795. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75796. // truncated at around 1.3% of peak strength.
  75797. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75798. var sigma = (1 / 3);
  75799. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75800. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75801. var weight = (1.0 / denominator) * Math.exp(exponent);
  75802. return weight;
  75803. };
  75804. /**
  75805. * Generates a string that can be used as a floating point number in GLSL.
  75806. * @param x Value to print.
  75807. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75808. * @return GLSL float string.
  75809. */
  75810. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75811. if (decimalFigures === void 0) { decimalFigures = 8; }
  75812. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75813. };
  75814. return BlurPostProcess;
  75815. }(BABYLON.PostProcess));
  75816. BABYLON.BlurPostProcess = BlurPostProcess;
  75817. })(BABYLON || (BABYLON = {}));
  75818. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75819. var BABYLON;
  75820. (function (BABYLON) {
  75821. /**
  75822. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75823. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75824. * based on samples that have a large difference in distance than the center pixel.
  75825. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75826. */
  75827. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75828. __extends(DepthOfFieldBlurPostProcess, _super);
  75829. /**
  75830. * Creates a new instance CircleOfConfusionPostProcess
  75831. * @param name The name of the effect.
  75832. * @param scene The scene the effect belongs to.
  75833. * @param direction The direction the blur should be applied.
  75834. * @param kernel The size of the kernel used to blur.
  75835. * @param options The required width/height ratio to downsize to before computing the render pass.
  75836. * @param camera The camera to apply the render pass to.
  75837. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75838. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75839. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75840. * @param engine The engine which the post process will be applied. (default: current engine)
  75841. * @param reusable If the post process can be reused on the same frame. (default: false)
  75842. * @param textureType Type of textures used when performing the post process. (default: 0)
  75843. * @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)
  75844. */
  75845. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75846. if (imageToBlur === void 0) { imageToBlur = null; }
  75847. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75848. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75849. if (blockCompilation === void 0) { blockCompilation = false; }
  75850. 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;
  75851. _this.direction = direction;
  75852. _this.onApplyObservable.add(function (effect) {
  75853. if (imageToBlur != null) {
  75854. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75855. }
  75856. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75857. if (scene.activeCamera) {
  75858. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75859. }
  75860. });
  75861. return _this;
  75862. }
  75863. return DepthOfFieldBlurPostProcess;
  75864. }(BABYLON.BlurPostProcess));
  75865. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75866. })(BABYLON || (BABYLON = {}));
  75867. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75868. var BABYLON;
  75869. (function (BABYLON) {
  75870. /**
  75871. * Options to be set when merging outputs from the default pipeline.
  75872. */
  75873. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75874. function DepthOfFieldMergePostProcessOptions() {
  75875. }
  75876. return DepthOfFieldMergePostProcessOptions;
  75877. }());
  75878. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75879. /**
  75880. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75881. */
  75882. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75883. __extends(DepthOfFieldMergePostProcess, _super);
  75884. /**
  75885. * Creates a new instance of DepthOfFieldMergePostProcess
  75886. * @param name The name of the effect.
  75887. * @param originalFromInput Post process which's input will be used for the merge.
  75888. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75889. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75890. * @param options The required width/height ratio to downsize to before computing the render pass.
  75891. * @param camera The camera to apply the render pass to.
  75892. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75893. * @param engine The engine which the post process will be applied. (default: current engine)
  75894. * @param reusable If the post process can be reused on the same frame. (default: false)
  75895. * @param textureType Type of textures used when performing the post process. (default: 0)
  75896. * @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)
  75897. */
  75898. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75899. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75900. if (blockCompilation === void 0) { blockCompilation = false; }
  75901. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75902. _this.blurSteps = blurSteps;
  75903. _this.onApplyObservable.add(function (effect) {
  75904. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75905. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75906. blurSteps.forEach(function (step, index) {
  75907. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75908. });
  75909. });
  75910. if (!blockCompilation) {
  75911. _this.updateEffect();
  75912. }
  75913. return _this;
  75914. }
  75915. /**
  75916. * Updates the effect with the current post process compile time values and recompiles the shader.
  75917. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75918. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75919. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75920. * @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
  75921. * @param onCompiled Called when the shader has been compiled.
  75922. * @param onError Called if there is an error when compiling a shader.
  75923. */
  75924. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75925. if (defines === void 0) { defines = null; }
  75926. if (uniforms === void 0) { uniforms = null; }
  75927. if (samplers === void 0) { samplers = null; }
  75928. if (!defines) {
  75929. defines = "";
  75930. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75931. }
  75932. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75933. };
  75934. return DepthOfFieldMergePostProcess;
  75935. }(BABYLON.PostProcess));
  75936. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75937. })(BABYLON || (BABYLON = {}));
  75938. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75939. var BABYLON;
  75940. (function (BABYLON) {
  75941. /**
  75942. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75943. */
  75944. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75945. __extends(CircleOfConfusionPostProcess, _super);
  75946. /**
  75947. * Creates a new instance CircleOfConfusionPostProcess
  75948. * @param name The name of the effect.
  75949. * @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.
  75950. * @param options The required width/height ratio to downsize to before computing the render pass.
  75951. * @param camera The camera to apply the render pass to.
  75952. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75953. * @param engine The engine which the post process will be applied. (default: current engine)
  75954. * @param reusable If the post process can be reused on the same frame. (default: false)
  75955. * @param textureType Type of textures used when performing the post process. (default: 0)
  75956. * @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)
  75957. */
  75958. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75959. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75960. if (blockCompilation === void 0) { blockCompilation = false; }
  75961. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75962. /**
  75963. * 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.
  75964. */
  75965. _this.lensSize = 50;
  75966. /**
  75967. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75968. */
  75969. _this.fStop = 1.4;
  75970. /**
  75971. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75972. */
  75973. _this.focusDistance = 2000;
  75974. /**
  75975. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75976. */
  75977. _this.focalLength = 50;
  75978. _this._depthTexture = null;
  75979. _this._depthTexture = depthTexture;
  75980. _this.onApplyObservable.add(function (effect) {
  75981. if (!_this._depthTexture) {
  75982. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75983. return;
  75984. }
  75985. effect.setTexture("depthSampler", _this._depthTexture);
  75986. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75987. var aperture = _this.lensSize / _this.fStop;
  75988. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75989. effect.setFloat('focusDistance', _this.focusDistance);
  75990. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75991. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75992. });
  75993. return _this;
  75994. }
  75995. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75996. /**
  75997. * 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.
  75998. */
  75999. set: function (value) {
  76000. this._depthTexture = value;
  76001. },
  76002. enumerable: true,
  76003. configurable: true
  76004. });
  76005. return CircleOfConfusionPostProcess;
  76006. }(BABYLON.PostProcess));
  76007. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  76008. })(BABYLON || (BABYLON = {}));
  76009. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  76010. var BABYLON;
  76011. (function (BABYLON) {
  76012. /**
  76013. * Specifies the level of max blur that should be applied when using the depth of field effect
  76014. */
  76015. var DepthOfFieldEffectBlurLevel;
  76016. (function (DepthOfFieldEffectBlurLevel) {
  76017. /**
  76018. * Subtle blur
  76019. */
  76020. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  76021. /**
  76022. * Medium blur
  76023. */
  76024. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  76025. /**
  76026. * Large blur
  76027. */
  76028. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  76029. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  76030. ;
  76031. /**
  76032. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  76033. */
  76034. var DepthOfFieldEffect = /** @class */ (function (_super) {
  76035. __extends(DepthOfFieldEffect, _super);
  76036. /**
  76037. * Creates a new instance DepthOfFieldEffect
  76038. * @param scene The scene the effect belongs to.
  76039. * @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.
  76040. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76041. * @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)
  76042. */
  76043. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  76044. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  76045. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76046. if (blockCompilation === void 0) { blockCompilation = false; }
  76047. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  76048. return _this._effects;
  76049. }, true) || this;
  76050. /**
  76051. * Internal post processes in depth of field effect
  76052. */
  76053. _this._effects = [];
  76054. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  76055. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76056. // 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)
  76057. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  76058. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  76059. _this._depthOfFieldBlurY = [];
  76060. _this._depthOfFieldBlurX = [];
  76061. var blurCount = 1;
  76062. var kernelSize = 15;
  76063. switch (blurLevel) {
  76064. case DepthOfFieldEffectBlurLevel.High: {
  76065. blurCount = 3;
  76066. kernelSize = 51;
  76067. break;
  76068. }
  76069. case DepthOfFieldEffectBlurLevel.Medium: {
  76070. blurCount = 2;
  76071. kernelSize = 31;
  76072. break;
  76073. }
  76074. default: {
  76075. kernelSize = 15;
  76076. blurCount = 1;
  76077. break;
  76078. }
  76079. }
  76080. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  76081. var ratio = 1.0;
  76082. for (var i = 0; i < blurCount; i++) {
  76083. 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);
  76084. blurY.autoClear = false;
  76085. ratio = 0.75 / Math.pow(2, i);
  76086. 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);
  76087. blurX.autoClear = false;
  76088. _this._depthOfFieldBlurY.push(blurY);
  76089. _this._depthOfFieldBlurX.push(blurX);
  76090. }
  76091. // Set all post processes on the effect.
  76092. _this._effects = [_this._circleOfConfusion];
  76093. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  76094. _this._effects.push(_this._depthOfFieldBlurY[i]);
  76095. _this._effects.push(_this._depthOfFieldBlurX[i]);
  76096. }
  76097. // Merge blurred images with original image based on circleOfConfusion
  76098. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76099. _this._dofMerge.autoClear = false;
  76100. _this._effects.push(_this._dofMerge);
  76101. return _this;
  76102. }
  76103. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  76104. get: function () {
  76105. return this._circleOfConfusion.focalLength;
  76106. },
  76107. /**
  76108. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  76109. */
  76110. set: function (value) {
  76111. this._circleOfConfusion.focalLength = value;
  76112. },
  76113. enumerable: true,
  76114. configurable: true
  76115. });
  76116. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  76117. get: function () {
  76118. return this._circleOfConfusion.fStop;
  76119. },
  76120. /**
  76121. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  76122. */
  76123. set: function (value) {
  76124. this._circleOfConfusion.fStop = value;
  76125. },
  76126. enumerable: true,
  76127. configurable: true
  76128. });
  76129. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  76130. get: function () {
  76131. return this._circleOfConfusion.focusDistance;
  76132. },
  76133. /**
  76134. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  76135. */
  76136. set: function (value) {
  76137. this._circleOfConfusion.focusDistance = value;
  76138. },
  76139. enumerable: true,
  76140. configurable: true
  76141. });
  76142. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  76143. get: function () {
  76144. return this._circleOfConfusion.lensSize;
  76145. },
  76146. /**
  76147. * 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.
  76148. */
  76149. set: function (value) {
  76150. this._circleOfConfusion.lensSize = value;
  76151. },
  76152. enumerable: true,
  76153. configurable: true
  76154. });
  76155. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  76156. /**
  76157. * 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.
  76158. */
  76159. set: function (value) {
  76160. this._circleOfConfusion.depthTexture = value;
  76161. },
  76162. enumerable: true,
  76163. configurable: true
  76164. });
  76165. /**
  76166. * Disposes each of the internal effects for a given camera.
  76167. * @param camera The camera to dispose the effect on.
  76168. */
  76169. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  76170. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76171. this._effects[effectIndex].dispose(camera);
  76172. }
  76173. };
  76174. /**
  76175. * Internal
  76176. */
  76177. DepthOfFieldEffect.prototype._updateEffects = function () {
  76178. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76179. this._effects[effectIndex].updateEffect();
  76180. }
  76181. };
  76182. /**
  76183. * Internal
  76184. * @returns if all the contained post processes are ready.
  76185. */
  76186. DepthOfFieldEffect.prototype._isReady = function () {
  76187. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76188. if (!this._effects[effectIndex].isReady()) {
  76189. return false;
  76190. }
  76191. }
  76192. return true;
  76193. };
  76194. return DepthOfFieldEffect;
  76195. }(BABYLON.PostProcessRenderEffect));
  76196. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  76197. })(BABYLON || (BABYLON = {}));
  76198. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  76199. var BABYLON;
  76200. (function (BABYLON) {
  76201. /**
  76202. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76203. */
  76204. var BloomMergePostProcess = /** @class */ (function (_super) {
  76205. __extends(BloomMergePostProcess, _super);
  76206. /**
  76207. * Creates a new instance of @see BloomMergePostProcess
  76208. * @param name The name of the effect.
  76209. * @param originalFromInput Post process which's input will be used for the merge.
  76210. * @param blurred Blurred highlights post process which's output will be used.
  76211. * @param weight Weight of the bloom to be added to the original input.
  76212. * @param options The required width/height ratio to downsize to before computing the render pass.
  76213. * @param camera The camera to apply the render pass to.
  76214. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76215. * @param engine The engine which the post process will be applied. (default: current engine)
  76216. * @param reusable If the post process can be reused on the same frame. (default: false)
  76217. * @param textureType Type of textures used when performing the post process. (default: 0)
  76218. * @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)
  76219. */
  76220. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76221. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76222. if (blockCompilation === void 0) { blockCompilation = false; }
  76223. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76224. _this.weight = weight;
  76225. _this.onApplyObservable.add(function (effect) {
  76226. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76227. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  76228. effect.setFloat("bloomWeight", _this.weight);
  76229. });
  76230. if (!blockCompilation) {
  76231. _this.updateEffect();
  76232. }
  76233. return _this;
  76234. }
  76235. return BloomMergePostProcess;
  76236. }(BABYLON.PostProcess));
  76237. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  76238. })(BABYLON || (BABYLON = {}));
  76239. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  76240. var BABYLON;
  76241. (function (BABYLON) {
  76242. /**
  76243. * 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.
  76244. */
  76245. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  76246. __extends(ExtractHighlightsPostProcess, _super);
  76247. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76248. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76249. if (blockCompilation === void 0) { blockCompilation = false; }
  76250. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76251. /**
  76252. * The luminance threshold, pixels below this value will be set to black.
  76253. */
  76254. _this.threshold = 0.9;
  76255. /**
  76256. * Internal
  76257. */
  76258. _this._exposure = 1;
  76259. /**
  76260. * Post process which has the input texture to be used when performing highlight extraction
  76261. */
  76262. _this._inputPostProcess = null;
  76263. _this.onApplyObservable.add(function (effect) {
  76264. if (_this._inputPostProcess) {
  76265. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  76266. }
  76267. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  76268. effect.setFloat('exposure', _this._exposure);
  76269. });
  76270. return _this;
  76271. }
  76272. return ExtractHighlightsPostProcess;
  76273. }(BABYLON.PostProcess));
  76274. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  76275. })(BABYLON || (BABYLON = {}));
  76276. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  76277. var BABYLON;
  76278. (function (BABYLON) {
  76279. /**
  76280. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  76281. */
  76282. var BloomEffect = /** @class */ (function (_super) {
  76283. __extends(BloomEffect, _super);
  76284. /**
  76285. * Creates a new instance of @see BloomEffect
  76286. * @param scene The scene the effect belongs to.
  76287. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  76288. * @param bloomKernel The size of the kernel to be used when applying the blur.
  76289. * @param bloomWeight The the strength of bloom.
  76290. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76291. * @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)
  76292. */
  76293. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  76294. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76295. if (blockCompilation === void 0) { blockCompilation = false; }
  76296. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  76297. return _this._effects;
  76298. }, true) || this;
  76299. _this.bloomScale = bloomScale;
  76300. /**
  76301. * Internal
  76302. */
  76303. _this._effects = [];
  76304. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76305. _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);
  76306. _this._blurX.alwaysForcePOT = true;
  76307. _this._blurX.autoClear = false;
  76308. _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);
  76309. _this._blurY.alwaysForcePOT = true;
  76310. _this._blurY.autoClear = false;
  76311. _this.kernel = bloomKernel;
  76312. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  76313. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76314. _this._merge.autoClear = false;
  76315. _this._effects.push(_this._merge);
  76316. return _this;
  76317. }
  76318. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76319. /**
  76320. * The luminance threshold to find bright areas of the image to bloom.
  76321. */
  76322. get: function () {
  76323. return this._downscale.threshold;
  76324. },
  76325. set: function (value) {
  76326. this._downscale.threshold = value;
  76327. },
  76328. enumerable: true,
  76329. configurable: true
  76330. });
  76331. Object.defineProperty(BloomEffect.prototype, "weight", {
  76332. /**
  76333. * The strength of the bloom.
  76334. */
  76335. get: function () {
  76336. return this._merge.weight;
  76337. },
  76338. set: function (value) {
  76339. this._merge.weight = value;
  76340. },
  76341. enumerable: true,
  76342. configurable: true
  76343. });
  76344. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76345. /**
  76346. * Specifies the size of the bloom blur kernel, relative to the final output size
  76347. */
  76348. get: function () {
  76349. return this._blurX.kernel / this.bloomScale;
  76350. },
  76351. set: function (value) {
  76352. this._blurX.kernel = value * this.bloomScale;
  76353. this._blurY.kernel = value * this.bloomScale;
  76354. },
  76355. enumerable: true,
  76356. configurable: true
  76357. });
  76358. /**
  76359. * Disposes each of the internal effects for a given camera.
  76360. * @param camera The camera to dispose the effect on.
  76361. */
  76362. BloomEffect.prototype.disposeEffects = function (camera) {
  76363. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76364. this._effects[effectIndex].dispose(camera);
  76365. }
  76366. };
  76367. /**
  76368. * Internal
  76369. */
  76370. BloomEffect.prototype._updateEffects = function () {
  76371. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76372. this._effects[effectIndex].updateEffect();
  76373. }
  76374. };
  76375. /**
  76376. * Internal
  76377. * @returns if all the contained post processes are ready.
  76378. */
  76379. BloomEffect.prototype._isReady = function () {
  76380. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76381. if (!this._effects[effectIndex].isReady()) {
  76382. return false;
  76383. }
  76384. }
  76385. return true;
  76386. };
  76387. return BloomEffect;
  76388. }(BABYLON.PostProcessRenderEffect));
  76389. BABYLON.BloomEffect = BloomEffect;
  76390. })(BABYLON || (BABYLON = {}));
  76391. //# sourceMappingURL=babylon.bloomEffect.js.map
  76392. var BABYLON;
  76393. (function (BABYLON) {
  76394. /**
  76395. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76396. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76397. */
  76398. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76399. __extends(DefaultRenderingPipeline, _super);
  76400. /**
  76401. * @constructor
  76402. * @param {string} name - The rendering pipeline name (default: "")
  76403. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76404. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76405. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76406. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76407. */
  76408. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76409. if (name === void 0) { name = ""; }
  76410. if (hdr === void 0) { hdr = true; }
  76411. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76412. if (automaticBuild === void 0) { automaticBuild = true; }
  76413. var _this = _super.call(this, scene.getEngine(), name) || this;
  76414. _this._camerasToBeAttached = [];
  76415. /**
  76416. * ID of the sharpen post process,
  76417. */
  76418. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76419. /**
  76420. * ID of the image processing post process;
  76421. */
  76422. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76423. /**
  76424. * ID of the Fast Approximate Anti-Aliasing post process;
  76425. */
  76426. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76427. /**
  76428. * ID of the chromatic aberration post process,
  76429. */
  76430. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76431. /**
  76432. * ID of the grain post process
  76433. */
  76434. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76435. /**
  76436. * Glow post process which adds a glow to emmisive areas of the image
  76437. */
  76438. _this._glowLayer = null;
  76439. /**
  76440. * Animations which can be used to tweak settings over a period of time
  76441. */
  76442. _this.animations = [];
  76443. _this._imageProcessingConfigurationObserver = null;
  76444. // Values
  76445. _this._sharpenEnabled = false;
  76446. _this._bloomEnabled = false;
  76447. _this._depthOfFieldEnabled = false;
  76448. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76449. _this._fxaaEnabled = false;
  76450. _this._imageProcessingEnabled = true;
  76451. _this._bloomScale = 0.5;
  76452. _this._chromaticAberrationEnabled = false;
  76453. _this._grainEnabled = false;
  76454. _this._buildAllowed = true;
  76455. _this._resizeObserver = null;
  76456. _this._hardwareScaleLevel = 1.0;
  76457. _this._bloomKernel = 64;
  76458. /**
  76459. * Specifies the weight of the bloom in the final rendering
  76460. */
  76461. _this._bloomWeight = 0.15;
  76462. /**
  76463. * Specifies the luma threshold for the area that will be blurred by the bloom
  76464. */
  76465. _this._bloomThreshold = 0.9;
  76466. _this._samples = 1;
  76467. _this._hasCleared = false;
  76468. _this._prevPostProcess = null;
  76469. _this._prevPrevPostProcess = null;
  76470. _this._cameras = cameras || scene.cameras;
  76471. _this._camerasToBeAttached = _this._cameras.slice();
  76472. _this._buildAllowed = automaticBuild;
  76473. // Initialize
  76474. _this._scene = scene;
  76475. var caps = _this._scene.getEngine().getCaps();
  76476. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76477. // Misc
  76478. if (_this._hdr) {
  76479. if (caps.textureHalfFloatRender) {
  76480. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76481. }
  76482. else if (caps.textureFloatRender) {
  76483. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76484. }
  76485. }
  76486. else {
  76487. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76488. }
  76489. // Attach
  76490. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76491. var engine = _this._scene.getEngine();
  76492. // Create post processes before hand so they can be modified before enabled.
  76493. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76494. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76495. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76496. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76497. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76498. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76499. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76500. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76501. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76502. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76503. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76504. _this.bloomKernel = _this.bloomKernel;
  76505. });
  76506. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76507. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76508. });
  76509. _this._buildPipeline();
  76510. return _this;
  76511. }
  76512. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76513. get: function () {
  76514. return this._sharpenEnabled;
  76515. },
  76516. /**
  76517. * Enable or disable the sharpen process from the pipeline
  76518. */
  76519. set: function (enabled) {
  76520. if (this._sharpenEnabled === enabled) {
  76521. return;
  76522. }
  76523. this._sharpenEnabled = enabled;
  76524. this._buildPipeline();
  76525. },
  76526. enumerable: true,
  76527. configurable: true
  76528. });
  76529. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76530. /**
  76531. * Specifies the size of the bloom blur kernel, relative to the final output size
  76532. */
  76533. get: function () {
  76534. return this._bloomKernel;
  76535. },
  76536. set: function (value) {
  76537. this._bloomKernel = value;
  76538. this.bloom.kernel = value / this._hardwareScaleLevel;
  76539. },
  76540. enumerable: true,
  76541. configurable: true
  76542. });
  76543. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76544. get: function () {
  76545. return this._bloomWeight;
  76546. },
  76547. /**
  76548. * The strength of the bloom.
  76549. */
  76550. set: function (value) {
  76551. if (this._bloomWeight === value) {
  76552. return;
  76553. }
  76554. this.bloom.weight = value;
  76555. this._bloomWeight = value;
  76556. },
  76557. enumerable: true,
  76558. configurable: true
  76559. });
  76560. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76561. get: function () {
  76562. return this._bloomThreshold;
  76563. },
  76564. /**
  76565. * The strength of the bloom.
  76566. */
  76567. set: function (value) {
  76568. if (this._bloomThreshold === value) {
  76569. return;
  76570. }
  76571. this.bloom.threshold = value;
  76572. this._bloomThreshold = value;
  76573. },
  76574. enumerable: true,
  76575. configurable: true
  76576. });
  76577. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76578. get: function () {
  76579. return this._bloomScale;
  76580. },
  76581. /**
  76582. * The scale of the bloom, lower value will provide better performance.
  76583. */
  76584. set: function (value) {
  76585. if (this._bloomScale === value) {
  76586. return;
  76587. }
  76588. this._bloomScale = value;
  76589. // recreate bloom and dispose old as this setting is not dynamic
  76590. this._rebuildBloom();
  76591. this._buildPipeline();
  76592. },
  76593. enumerable: true,
  76594. configurable: true
  76595. });
  76596. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76597. get: function () {
  76598. return this._bloomEnabled;
  76599. },
  76600. /**
  76601. * Enable or disable the bloom from the pipeline
  76602. */
  76603. set: function (enabled) {
  76604. if (this._bloomEnabled === enabled) {
  76605. return;
  76606. }
  76607. this._bloomEnabled = enabled;
  76608. this._buildPipeline();
  76609. },
  76610. enumerable: true,
  76611. configurable: true
  76612. });
  76613. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76614. // recreate bloom and dispose old as this setting is not dynamic
  76615. var oldBloom = this.bloom;
  76616. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76617. this.bloom.threshold = oldBloom.threshold;
  76618. for (var i = 0; i < this._cameras.length; i++) {
  76619. oldBloom.disposeEffects(this._cameras[i]);
  76620. }
  76621. };
  76622. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76623. /**
  76624. * If the depth of field is enabled.
  76625. */
  76626. get: function () {
  76627. return this._depthOfFieldEnabled;
  76628. },
  76629. set: function (enabled) {
  76630. if (this._depthOfFieldEnabled === enabled) {
  76631. return;
  76632. }
  76633. this._depthOfFieldEnabled = enabled;
  76634. this._buildPipeline();
  76635. },
  76636. enumerable: true,
  76637. configurable: true
  76638. });
  76639. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76640. /**
  76641. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76642. */
  76643. get: function () {
  76644. return this._depthOfFieldBlurLevel;
  76645. },
  76646. set: function (value) {
  76647. if (this._depthOfFieldBlurLevel === value) {
  76648. return;
  76649. }
  76650. this._depthOfFieldBlurLevel = value;
  76651. // recreate dof and dispose old as this setting is not dynamic
  76652. var oldDof = this.depthOfField;
  76653. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76654. this.depthOfField.focalLength = oldDof.focalLength;
  76655. this.depthOfField.focusDistance = oldDof.focusDistance;
  76656. this.depthOfField.fStop = oldDof.fStop;
  76657. this.depthOfField.lensSize = oldDof.lensSize;
  76658. for (var i = 0; i < this._cameras.length; i++) {
  76659. oldDof.disposeEffects(this._cameras[i]);
  76660. }
  76661. this._buildPipeline();
  76662. },
  76663. enumerable: true,
  76664. configurable: true
  76665. });
  76666. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76667. get: function () {
  76668. return this._fxaaEnabled;
  76669. },
  76670. /**
  76671. * If the anti aliasing is enabled.
  76672. */
  76673. set: function (enabled) {
  76674. if (this._fxaaEnabled === enabled) {
  76675. return;
  76676. }
  76677. this._fxaaEnabled = enabled;
  76678. this._buildPipeline();
  76679. },
  76680. enumerable: true,
  76681. configurable: true
  76682. });
  76683. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76684. get: function () {
  76685. return this._samples;
  76686. },
  76687. /**
  76688. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76689. */
  76690. set: function (sampleCount) {
  76691. if (this._samples === sampleCount) {
  76692. return;
  76693. }
  76694. this._samples = sampleCount;
  76695. this._buildPipeline();
  76696. },
  76697. enumerable: true,
  76698. configurable: true
  76699. });
  76700. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76701. get: function () {
  76702. return this._imageProcessingEnabled;
  76703. },
  76704. /**
  76705. * If image processing is enabled.
  76706. */
  76707. set: function (enabled) {
  76708. if (this._imageProcessingEnabled === enabled) {
  76709. return;
  76710. }
  76711. this._imageProcessingEnabled = enabled;
  76712. this._buildPipeline();
  76713. },
  76714. enumerable: true,
  76715. configurable: true
  76716. });
  76717. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76718. get: function () {
  76719. return this._glowLayer == null;
  76720. },
  76721. /**
  76722. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76723. */
  76724. set: function (enabled) {
  76725. if (enabled && !this._glowLayer) {
  76726. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76727. }
  76728. else if (!enabled && this._glowLayer) {
  76729. this._glowLayer.dispose();
  76730. this._glowLayer = null;
  76731. }
  76732. },
  76733. enumerable: true,
  76734. configurable: true
  76735. });
  76736. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76737. get: function () {
  76738. return this._chromaticAberrationEnabled;
  76739. },
  76740. /**
  76741. * Enable or disable the chromaticAberration process from the pipeline
  76742. */
  76743. set: function (enabled) {
  76744. if (this._chromaticAberrationEnabled === enabled) {
  76745. return;
  76746. }
  76747. this._chromaticAberrationEnabled = enabled;
  76748. this._buildPipeline();
  76749. },
  76750. enumerable: true,
  76751. configurable: true
  76752. });
  76753. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76754. get: function () {
  76755. return this._grainEnabled;
  76756. },
  76757. /**
  76758. * Enable or disable the grain process from the pipeline
  76759. */
  76760. set: function (enabled) {
  76761. if (this._grainEnabled === enabled) {
  76762. return;
  76763. }
  76764. this._grainEnabled = enabled;
  76765. this._buildPipeline();
  76766. },
  76767. enumerable: true,
  76768. configurable: true
  76769. });
  76770. /**
  76771. * Force the compilation of the entire pipeline.
  76772. */
  76773. DefaultRenderingPipeline.prototype.prepare = function () {
  76774. var previousState = this._buildAllowed;
  76775. this._buildAllowed = true;
  76776. this._buildPipeline();
  76777. this._buildAllowed = previousState;
  76778. };
  76779. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76780. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76781. if (this._hasCleared) {
  76782. postProcess.autoClear = false;
  76783. }
  76784. else {
  76785. postProcess.autoClear = true;
  76786. this._scene.autoClear = false;
  76787. this._hasCleared = true;
  76788. }
  76789. if (!skipTextureSharing) {
  76790. if (this._prevPrevPostProcess) {
  76791. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76792. }
  76793. else {
  76794. postProcess.useOwnOutput();
  76795. }
  76796. if (this._prevPostProcess) {
  76797. this._prevPrevPostProcess = this._prevPostProcess;
  76798. }
  76799. this._prevPostProcess = postProcess;
  76800. }
  76801. };
  76802. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76803. var _this = this;
  76804. if (!this._buildAllowed) {
  76805. return;
  76806. }
  76807. this._scene.autoClear = true;
  76808. var engine = this._scene.getEngine();
  76809. this._disposePostProcesses();
  76810. if (this._cameras !== null) {
  76811. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76812. // get back cameras to be used to reattach pipeline
  76813. this._cameras = this._camerasToBeAttached.slice();
  76814. }
  76815. this._reset();
  76816. this._prevPostProcess = null;
  76817. this._prevPrevPostProcess = null;
  76818. this._hasCleared = false;
  76819. if (this.depthOfFieldEnabled) {
  76820. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76821. this.depthOfField.depthTexture = depthTexture;
  76822. if (!this.depthOfField._isReady()) {
  76823. this.depthOfField._updateEffects();
  76824. }
  76825. this.addEffect(this.depthOfField);
  76826. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76827. }
  76828. if (this.bloomEnabled) {
  76829. if (!this.bloom._isReady()) {
  76830. this.bloom._updateEffects();
  76831. }
  76832. this.addEffect(this.bloom);
  76833. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76834. }
  76835. if (this._imageProcessingEnabled) {
  76836. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76837. if (this._hdr) {
  76838. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76839. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76840. }
  76841. else {
  76842. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76843. }
  76844. }
  76845. if (this.sharpenEnabled) {
  76846. if (!this.sharpen.isReady()) {
  76847. this.sharpen.updateEffect();
  76848. }
  76849. this.addEffect(this._sharpenEffect);
  76850. this._setAutoClearAndTextureSharing(this.sharpen);
  76851. }
  76852. if (this.grainEnabled) {
  76853. if (!this.grain.isReady()) {
  76854. this.grain.updateEffect();
  76855. }
  76856. this.addEffect(this._grainEffect);
  76857. this._setAutoClearAndTextureSharing(this.grain);
  76858. }
  76859. if (this.chromaticAberrationEnabled) {
  76860. if (!this.chromaticAberration.isReady()) {
  76861. this.chromaticAberration.updateEffect();
  76862. }
  76863. this.addEffect(this._chromaticAberrationEffect);
  76864. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76865. }
  76866. if (this.fxaaEnabled) {
  76867. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76868. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76869. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76870. }
  76871. if (this._cameras !== null) {
  76872. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76873. }
  76874. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76875. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76876. }
  76877. };
  76878. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76879. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76880. for (var i = 0; i < this._cameras.length; i++) {
  76881. var camera = this._cameras[i];
  76882. if (this.imageProcessing) {
  76883. this.imageProcessing.dispose(camera);
  76884. }
  76885. if (this.fxaa) {
  76886. this.fxaa.dispose(camera);
  76887. }
  76888. // These are created in the constructor and should not be disposed on every pipeline change
  76889. if (disposeNonRecreated) {
  76890. if (this.sharpen) {
  76891. this.sharpen.dispose(camera);
  76892. }
  76893. if (this.depthOfField) {
  76894. this.depthOfField.disposeEffects(camera);
  76895. }
  76896. if (this.bloom) {
  76897. this.bloom.disposeEffects(camera);
  76898. }
  76899. if (this.chromaticAberration) {
  76900. this.chromaticAberration.dispose(camera);
  76901. }
  76902. if (this.grain) {
  76903. this.grain.dispose(camera);
  76904. }
  76905. if (this._glowLayer) {
  76906. this._glowLayer.dispose();
  76907. }
  76908. }
  76909. }
  76910. this.imageProcessing = null;
  76911. this.fxaa = null;
  76912. if (disposeNonRecreated) {
  76913. this.sharpen = null;
  76914. this._sharpenEffect = null;
  76915. this.depthOfField = null;
  76916. this.bloom = null;
  76917. this.chromaticAberration = null;
  76918. this._chromaticAberrationEffect = null;
  76919. this.grain = null;
  76920. this._grainEffect = null;
  76921. this._glowLayer = null;
  76922. }
  76923. };
  76924. /**
  76925. * Adds a camera to the pipeline
  76926. * @param camera the camera to be added
  76927. */
  76928. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  76929. this._camerasToBeAttached.push(camera);
  76930. this._buildPipeline();
  76931. };
  76932. /**
  76933. * Removes a camera from the pipeline
  76934. * @param camera the camera to remove
  76935. */
  76936. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  76937. var index = this._camerasToBeAttached.indexOf(camera);
  76938. this._camerasToBeAttached.splice(index, 1);
  76939. this._buildPipeline();
  76940. };
  76941. /**
  76942. * Dispose of the pipeline and stop all post processes
  76943. */
  76944. DefaultRenderingPipeline.prototype.dispose = function () {
  76945. this._disposePostProcesses(true);
  76946. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76947. this._scene.autoClear = true;
  76948. if (this._resizeObserver) {
  76949. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76950. this._resizeObserver = null;
  76951. }
  76952. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76953. _super.prototype.dispose.call(this);
  76954. };
  76955. /**
  76956. * Serialize the rendering pipeline (Used when exporting)
  76957. * @returns the serialized object
  76958. */
  76959. DefaultRenderingPipeline.prototype.serialize = function () {
  76960. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76961. serializationObject.customType = "DefaultRenderingPipeline";
  76962. return serializationObject;
  76963. };
  76964. /**
  76965. * Parse the serialized pipeline
  76966. * @param source Source pipeline.
  76967. * @param scene The scene to load the pipeline to.
  76968. * @param rootUrl The URL of the serialized pipeline.
  76969. * @returns An instantiated pipeline from the serialized object.
  76970. */
  76971. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76972. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76973. };
  76974. __decorate([
  76975. BABYLON.serialize()
  76976. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76977. __decorate([
  76978. BABYLON.serialize()
  76979. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76980. __decorate([
  76981. BABYLON.serialize()
  76982. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76983. __decorate([
  76984. BABYLON.serialize()
  76985. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76986. __decorate([
  76987. BABYLON.serialize()
  76988. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76989. __decorate([
  76990. BABYLON.serialize()
  76991. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76992. __decorate([
  76993. BABYLON.serialize()
  76994. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76995. __decorate([
  76996. BABYLON.serialize()
  76997. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76998. __decorate([
  76999. BABYLON.serialize()
  77000. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  77001. __decorate([
  77002. BABYLON.serialize()
  77003. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  77004. __decorate([
  77005. BABYLON.serialize()
  77006. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  77007. __decorate([
  77008. BABYLON.serialize()
  77009. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  77010. __decorate([
  77011. BABYLON.serialize()
  77012. ], DefaultRenderingPipeline.prototype, "samples", null);
  77013. __decorate([
  77014. BABYLON.serialize()
  77015. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  77016. __decorate([
  77017. BABYLON.serialize()
  77018. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  77019. __decorate([
  77020. BABYLON.serialize()
  77021. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  77022. __decorate([
  77023. BABYLON.serialize()
  77024. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  77025. return DefaultRenderingPipeline;
  77026. }(BABYLON.PostProcessRenderPipeline));
  77027. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  77028. })(BABYLON || (BABYLON = {}));
  77029. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  77030. var BABYLON;
  77031. (function (BABYLON) {
  77032. /**
  77033. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  77034. */
  77035. var GeometryBufferRenderer = /** @class */ (function () {
  77036. /**
  77037. * Creates a new G Buffer for the scene
  77038. * @param scene The scene the buffer belongs to
  77039. * @param ratio How big is the buffer related to the main canvas.
  77040. */
  77041. function GeometryBufferRenderer(scene, ratio) {
  77042. if (ratio === void 0) { ratio = 1; }
  77043. this._enablePosition = false;
  77044. this._scene = scene;
  77045. this._ratio = ratio;
  77046. // Render target
  77047. this._createRenderTargets();
  77048. }
  77049. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  77050. /**
  77051. * Set the render list (meshes to be rendered) used in the G buffer.
  77052. */
  77053. set: function (meshes) {
  77054. this._multiRenderTarget.renderList = meshes;
  77055. },
  77056. enumerable: true,
  77057. configurable: true
  77058. });
  77059. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  77060. /**
  77061. * Gets wether or not G buffer are supported by the running hardware.
  77062. * This requires draw buffer supports
  77063. */
  77064. get: function () {
  77065. return this._multiRenderTarget.isSupported;
  77066. },
  77067. enumerable: true,
  77068. configurable: true
  77069. });
  77070. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  77071. /**
  77072. * Gets wether or not position are enabled for the G buffer.
  77073. */
  77074. get: function () {
  77075. return this._enablePosition;
  77076. },
  77077. /**
  77078. * Sets wether or not position are enabled for the G buffer.
  77079. */
  77080. set: function (enable) {
  77081. this._enablePosition = enable;
  77082. this.dispose();
  77083. this._createRenderTargets();
  77084. },
  77085. enumerable: true,
  77086. configurable: true
  77087. });
  77088. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  77089. /**
  77090. * Gets the scene associated with the buffer.
  77091. */
  77092. get: function () {
  77093. return this._scene;
  77094. },
  77095. enumerable: true,
  77096. configurable: true
  77097. });
  77098. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  77099. /**
  77100. * Gets the ratio used by the buffer during its creation.
  77101. * How big is the buffer related to the main canvas.
  77102. */
  77103. get: function () {
  77104. return this._ratio;
  77105. },
  77106. enumerable: true,
  77107. configurable: true
  77108. });
  77109. /**
  77110. * Checks wether everything is ready to render a submesh to the G buffer.
  77111. * @param subMesh the submesh to check readiness for
  77112. * @param useInstances is the mesh drawn using instance or not
  77113. * @returns true if ready otherwise false
  77114. */
  77115. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  77116. var material = subMesh.getMaterial();
  77117. if (material && material.disableDepthWrite) {
  77118. return false;
  77119. }
  77120. var defines = [];
  77121. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  77122. var mesh = subMesh.getMesh();
  77123. // Alpha test
  77124. if (material && material.needAlphaTesting()) {
  77125. defines.push("#define ALPHATEST");
  77126. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77127. attribs.push(BABYLON.VertexBuffer.UVKind);
  77128. defines.push("#define UV1");
  77129. }
  77130. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77131. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77132. defines.push("#define UV2");
  77133. }
  77134. }
  77135. // Buffers
  77136. if (this._enablePosition) {
  77137. defines.push("#define POSITION");
  77138. }
  77139. // Bones
  77140. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77141. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77142. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77143. if (mesh.numBoneInfluencers > 4) {
  77144. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77145. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77146. }
  77147. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77148. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77149. }
  77150. else {
  77151. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77152. }
  77153. // Instances
  77154. if (useInstances) {
  77155. defines.push("#define INSTANCES");
  77156. attribs.push("world0");
  77157. attribs.push("world1");
  77158. attribs.push("world2");
  77159. attribs.push("world3");
  77160. }
  77161. // Get correct effect
  77162. var join = defines.join("\n");
  77163. if (this._cachedDefines !== join) {
  77164. this._cachedDefines = join;
  77165. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77166. }
  77167. return this._effect.isReady();
  77168. };
  77169. /**
  77170. * Gets the current underlying G Buffer.
  77171. * @returns the buffer
  77172. */
  77173. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77174. return this._multiRenderTarget;
  77175. };
  77176. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77177. /**
  77178. * Gets the number of samples used to render the buffer (anti aliasing).
  77179. */
  77180. get: function () {
  77181. return this._multiRenderTarget.samples;
  77182. },
  77183. /**
  77184. * Sets the number of samples used to render the buffer (anti aliasing).
  77185. */
  77186. set: function (value) {
  77187. this._multiRenderTarget.samples = value;
  77188. },
  77189. enumerable: true,
  77190. configurable: true
  77191. });
  77192. /**
  77193. * Disposes the renderer and frees up associated resources.
  77194. */
  77195. GeometryBufferRenderer.prototype.dispose = function () {
  77196. this.getGBuffer().dispose();
  77197. };
  77198. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77199. var _this = this;
  77200. var engine = this._scene.getEngine();
  77201. var count = this._enablePosition ? 3 : 2;
  77202. 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 });
  77203. if (!this.isSupported) {
  77204. return;
  77205. }
  77206. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77207. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77208. this._multiRenderTarget.refreshRate = 1;
  77209. this._multiRenderTarget.renderParticles = false;
  77210. this._multiRenderTarget.renderList = null;
  77211. // set default depth value to 1.0 (far away)
  77212. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77213. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77214. });
  77215. // Custom render function
  77216. var renderSubMesh = function (subMesh) {
  77217. var mesh = subMesh.getRenderingMesh();
  77218. var scene = _this._scene;
  77219. var engine = scene.getEngine();
  77220. var material = subMesh.getMaterial();
  77221. if (!material) {
  77222. return;
  77223. }
  77224. // Culling
  77225. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77226. // Managing instances
  77227. var batch = mesh._getInstancesRenderList(subMesh._id);
  77228. if (batch.mustReturn) {
  77229. return;
  77230. }
  77231. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77232. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77233. engine.enableEffect(_this._effect);
  77234. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77235. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77236. _this._effect.setMatrix("view", scene.getViewMatrix());
  77237. // Alpha test
  77238. if (material && material.needAlphaTesting()) {
  77239. var alphaTexture = material.getAlphaTestTexture();
  77240. if (alphaTexture) {
  77241. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77242. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77243. }
  77244. }
  77245. // Bones
  77246. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77247. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77248. }
  77249. // Draw
  77250. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77251. }
  77252. };
  77253. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77254. var index;
  77255. if (depthOnlySubMeshes.length) {
  77256. engine.setColorWrite(false);
  77257. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77258. renderSubMesh(depthOnlySubMeshes.data[index]);
  77259. }
  77260. engine.setColorWrite(true);
  77261. }
  77262. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77263. renderSubMesh(opaqueSubMeshes.data[index]);
  77264. }
  77265. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77266. renderSubMesh(alphaTestSubMeshes.data[index]);
  77267. }
  77268. };
  77269. };
  77270. return GeometryBufferRenderer;
  77271. }());
  77272. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77273. })(BABYLON || (BABYLON = {}));
  77274. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77275. var BABYLON;
  77276. (function (BABYLON) {
  77277. /**
  77278. * This groups together the common properties used for image processing either in direct forward pass
  77279. * or through post processing effect depending on the use of the image processing pipeline in your scene
  77280. * or not.
  77281. */
  77282. var ImageProcessingConfiguration = /** @class */ (function () {
  77283. function ImageProcessingConfiguration() {
  77284. /**
  77285. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  77286. */
  77287. this.colorCurves = new BABYLON.ColorCurves();
  77288. this._colorCurvesEnabled = false;
  77289. this._colorGradingEnabled = false;
  77290. this._colorGradingWithGreenDepth = true;
  77291. this._colorGradingBGR = true;
  77292. this._exposure = 1.0;
  77293. this._toneMappingEnabled = false;
  77294. this._contrast = 1.0;
  77295. /**
  77296. * Vignette stretch size.
  77297. */
  77298. this.vignetteStretch = 0;
  77299. /**
  77300. * Vignette centre X Offset.
  77301. */
  77302. this.vignetteCentreX = 0;
  77303. /**
  77304. * Vignette centre Y Offset.
  77305. */
  77306. this.vignetteCentreY = 0;
  77307. /**
  77308. * Vignette weight or intensity of the vignette effect.
  77309. */
  77310. this.vignetteWeight = 1.5;
  77311. /**
  77312. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77313. * if vignetteEnabled is set to true.
  77314. */
  77315. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  77316. /**
  77317. * Camera field of view used by the Vignette effect.
  77318. */
  77319. this.vignetteCameraFov = 0.5;
  77320. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  77321. this._vignetteEnabled = false;
  77322. this._applyByPostProcess = false;
  77323. this._isEnabled = true;
  77324. /**
  77325. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  77326. */
  77327. this.onUpdateParameters = new BABYLON.Observable();
  77328. }
  77329. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  77330. /**
  77331. * Gets wether the color curves effect is enabled.
  77332. */
  77333. get: function () {
  77334. return this._colorCurvesEnabled;
  77335. },
  77336. /**
  77337. * Sets wether the color curves effect is enabled.
  77338. */
  77339. set: function (value) {
  77340. if (this._colorCurvesEnabled === value) {
  77341. return;
  77342. }
  77343. this._colorCurvesEnabled = value;
  77344. this._updateParameters();
  77345. },
  77346. enumerable: true,
  77347. configurable: true
  77348. });
  77349. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  77350. /**
  77351. * Gets wether the color grading effect is enabled.
  77352. */
  77353. get: function () {
  77354. return this._colorGradingEnabled;
  77355. },
  77356. /**
  77357. * Sets wether the color grading effect is enabled.
  77358. */
  77359. set: function (value) {
  77360. if (this._colorGradingEnabled === value) {
  77361. return;
  77362. }
  77363. this._colorGradingEnabled = value;
  77364. this._updateParameters();
  77365. },
  77366. enumerable: true,
  77367. configurable: true
  77368. });
  77369. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  77370. /**
  77371. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  77372. */
  77373. get: function () {
  77374. return this._colorGradingWithGreenDepth;
  77375. },
  77376. /**
  77377. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  77378. */
  77379. set: function (value) {
  77380. if (this._colorGradingWithGreenDepth === value) {
  77381. return;
  77382. }
  77383. this._colorGradingWithGreenDepth = value;
  77384. this._updateParameters();
  77385. },
  77386. enumerable: true,
  77387. configurable: true
  77388. });
  77389. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  77390. /**
  77391. * Gets wether the color grading texture contains BGR values.
  77392. */
  77393. get: function () {
  77394. return this._colorGradingBGR;
  77395. },
  77396. /**
  77397. * Sets wether the color grading texture contains BGR values.
  77398. */
  77399. set: function (value) {
  77400. if (this._colorGradingBGR === value) {
  77401. return;
  77402. }
  77403. this._colorGradingBGR = value;
  77404. this._updateParameters();
  77405. },
  77406. enumerable: true,
  77407. configurable: true
  77408. });
  77409. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  77410. /**
  77411. * Gets the Exposure used in the effect.
  77412. */
  77413. get: function () {
  77414. return this._exposure;
  77415. },
  77416. /**
  77417. * Sets the Exposure used in the effect.
  77418. */
  77419. set: function (value) {
  77420. if (this._exposure === value) {
  77421. return;
  77422. }
  77423. this._exposure = value;
  77424. this._updateParameters();
  77425. },
  77426. enumerable: true,
  77427. configurable: true
  77428. });
  77429. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  77430. /**
  77431. * Gets wether the tone mapping effect is enabled.
  77432. */
  77433. get: function () {
  77434. return this._toneMappingEnabled;
  77435. },
  77436. /**
  77437. * Sets wether the tone mapping effect is enabled.
  77438. */
  77439. set: function (value) {
  77440. if (this._toneMappingEnabled === value) {
  77441. return;
  77442. }
  77443. this._toneMappingEnabled = value;
  77444. this._updateParameters();
  77445. },
  77446. enumerable: true,
  77447. configurable: true
  77448. });
  77449. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  77450. /**
  77451. * Gets the contrast used in the effect.
  77452. */
  77453. get: function () {
  77454. return this._contrast;
  77455. },
  77456. /**
  77457. * Sets the contrast used in the effect.
  77458. */
  77459. set: function (value) {
  77460. if (this._contrast === value) {
  77461. return;
  77462. }
  77463. this._contrast = value;
  77464. this._updateParameters();
  77465. },
  77466. enumerable: true,
  77467. configurable: true
  77468. });
  77469. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  77470. /**
  77471. * Gets the vignette blend mode allowing different kind of effect.
  77472. */
  77473. get: function () {
  77474. return this._vignetteBlendMode;
  77475. },
  77476. /**
  77477. * Sets the vignette blend mode allowing different kind of effect.
  77478. */
  77479. set: function (value) {
  77480. if (this._vignetteBlendMode === value) {
  77481. return;
  77482. }
  77483. this._vignetteBlendMode = value;
  77484. this._updateParameters();
  77485. },
  77486. enumerable: true,
  77487. configurable: true
  77488. });
  77489. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  77490. /**
  77491. * Gets wether the vignette effect is enabled.
  77492. */
  77493. get: function () {
  77494. return this._vignetteEnabled;
  77495. },
  77496. /**
  77497. * Sets wether the vignette effect is enabled.
  77498. */
  77499. set: function (value) {
  77500. if (this._vignetteEnabled === value) {
  77501. return;
  77502. }
  77503. this._vignetteEnabled = value;
  77504. this._updateParameters();
  77505. },
  77506. enumerable: true,
  77507. configurable: true
  77508. });
  77509. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  77510. /**
  77511. * Gets wether the image processing is applied through a post process or not.
  77512. */
  77513. get: function () {
  77514. return this._applyByPostProcess;
  77515. },
  77516. /**
  77517. * Sets wether the image processing is applied through a post process or not.
  77518. */
  77519. set: function (value) {
  77520. if (this._applyByPostProcess === value) {
  77521. return;
  77522. }
  77523. this._applyByPostProcess = value;
  77524. this._updateParameters();
  77525. },
  77526. enumerable: true,
  77527. configurable: true
  77528. });
  77529. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  77530. /**
  77531. * Gets wether the image processing is enabled or not.
  77532. */
  77533. get: function () {
  77534. return this._isEnabled;
  77535. },
  77536. /**
  77537. * Sets wether the image processing is enabled or not.
  77538. */
  77539. set: function (value) {
  77540. if (this._isEnabled === value) {
  77541. return;
  77542. }
  77543. this._isEnabled = value;
  77544. this._updateParameters();
  77545. },
  77546. enumerable: true,
  77547. configurable: true
  77548. });
  77549. /**
  77550. * Method called each time the image processing information changes requires to recompile the effect.
  77551. */
  77552. ImageProcessingConfiguration.prototype._updateParameters = function () {
  77553. this.onUpdateParameters.notifyObservers(this);
  77554. };
  77555. ImageProcessingConfiguration.prototype.getClassName = function () {
  77556. return "ImageProcessingConfiguration";
  77557. };
  77558. /**
  77559. * Prepare the list of uniforms associated with the Image Processing effects.
  77560. * @param uniformsList The list of uniforms used in the effect
  77561. * @param defines the list of defines currently in use
  77562. */
  77563. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  77564. if (defines.EXPOSURE) {
  77565. uniforms.push("exposureLinear");
  77566. }
  77567. if (defines.CONTRAST) {
  77568. uniforms.push("contrast");
  77569. }
  77570. if (defines.COLORGRADING) {
  77571. uniforms.push("colorTransformSettings");
  77572. }
  77573. if (defines.VIGNETTE) {
  77574. uniforms.push("vInverseScreenSize");
  77575. uniforms.push("vignetteSettings1");
  77576. uniforms.push("vignetteSettings2");
  77577. }
  77578. if (defines.COLORCURVES) {
  77579. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  77580. }
  77581. };
  77582. /**
  77583. * Prepare the list of samplers associated with the Image Processing effects.
  77584. * @param uniformsList The list of uniforms used in the effect
  77585. * @param defines the list of defines currently in use
  77586. */
  77587. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  77588. if (defines.COLORGRADING) {
  77589. samplersList.push("txColorTransform");
  77590. }
  77591. };
  77592. /**
  77593. * Prepare the list of defines associated to the shader.
  77594. * @param defines the list of defines to complete
  77595. */
  77596. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  77597. if (forPostProcess === void 0) { forPostProcess = false; }
  77598. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  77599. defines.VIGNETTE = false;
  77600. defines.TONEMAPPING = false;
  77601. defines.CONTRAST = false;
  77602. defines.EXPOSURE = false;
  77603. defines.COLORCURVES = false;
  77604. defines.COLORGRADING = false;
  77605. defines.COLORGRADING3D = false;
  77606. defines.IMAGEPROCESSING = false;
  77607. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  77608. return;
  77609. }
  77610. defines.VIGNETTE = this.vignetteEnabled;
  77611. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  77612. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  77613. defines.TONEMAPPING = this.toneMappingEnabled;
  77614. defines.CONTRAST = (this.contrast !== 1.0);
  77615. defines.EXPOSURE = (this.exposure !== 1.0);
  77616. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  77617. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  77618. if (defines.COLORGRADING) {
  77619. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  77620. }
  77621. else {
  77622. defines.COLORGRADING3D = false;
  77623. }
  77624. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  77625. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  77626. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  77627. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  77628. };
  77629. /**
  77630. * Returns true if all the image processing information are ready.
  77631. */
  77632. ImageProcessingConfiguration.prototype.isReady = function () {
  77633. // Color Grading texure can not be none blocking.
  77634. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  77635. };
  77636. /**
  77637. * Binds the image processing to the shader.
  77638. * @param effect The effect to bind to
  77639. */
  77640. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  77641. if (aspectRatio === void 0) { aspectRatio = 1; }
  77642. // Color Curves
  77643. if (this._colorCurvesEnabled && this.colorCurves) {
  77644. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  77645. }
  77646. // Vignette
  77647. if (this._vignetteEnabled) {
  77648. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  77649. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  77650. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  77651. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  77652. var vignetteScaleX = vignetteScaleY * aspectRatio;
  77653. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  77654. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  77655. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  77656. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  77657. var vignettePower = -2.0 * this.vignetteWeight;
  77658. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  77659. }
  77660. // Exposure
  77661. effect.setFloat("exposureLinear", this.exposure);
  77662. // Contrast
  77663. effect.setFloat("contrast", this.contrast);
  77664. // Color transform settings
  77665. if (this.colorGradingTexture) {
  77666. effect.setTexture("txColorTransform", this.colorGradingTexture);
  77667. var textureSize = this.colorGradingTexture.getSize().height;
  77668. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  77669. 0.5 / textureSize, // textureOffset
  77670. textureSize, // textureSize
  77671. this.colorGradingTexture.level // weight
  77672. );
  77673. }
  77674. };
  77675. /**
  77676. * Clones the current image processing instance.
  77677. * @return The cloned image processing
  77678. */
  77679. ImageProcessingConfiguration.prototype.clone = function () {
  77680. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  77681. };
  77682. /**
  77683. * Serializes the current image processing instance to a json representation.
  77684. * @return a JSON representation
  77685. */
  77686. ImageProcessingConfiguration.prototype.serialize = function () {
  77687. return BABYLON.SerializationHelper.Serialize(this);
  77688. };
  77689. /**
  77690. * Parses the image processing from a json representation.
  77691. * @param source the JSON source to parse
  77692. * @return The parsed image processing
  77693. */
  77694. ImageProcessingConfiguration.Parse = function (source) {
  77695. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  77696. };
  77697. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  77698. /**
  77699. * Used to apply the vignette as a mix with the pixel color.
  77700. */
  77701. get: function () {
  77702. return this._VIGNETTEMODE_MULTIPLY;
  77703. },
  77704. enumerable: true,
  77705. configurable: true
  77706. });
  77707. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  77708. /**
  77709. * Used to apply the vignette as a replacement of the pixel color.
  77710. */
  77711. get: function () {
  77712. return this._VIGNETTEMODE_OPAQUE;
  77713. },
  77714. enumerable: true,
  77715. configurable: true
  77716. });
  77717. // Static constants associated to the image processing.
  77718. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  77719. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  77720. __decorate([
  77721. BABYLON.serializeAsColorCurves()
  77722. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  77723. __decorate([
  77724. BABYLON.serialize()
  77725. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  77726. __decorate([
  77727. BABYLON.serializeAsTexture()
  77728. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  77729. __decorate([
  77730. BABYLON.serialize()
  77731. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  77732. __decorate([
  77733. BABYLON.serialize()
  77734. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  77735. __decorate([
  77736. BABYLON.serialize()
  77737. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  77738. __decorate([
  77739. BABYLON.serialize()
  77740. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  77741. __decorate([
  77742. BABYLON.serialize()
  77743. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  77744. __decorate([
  77745. BABYLON.serialize()
  77746. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  77747. __decorate([
  77748. BABYLON.serialize()
  77749. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  77750. __decorate([
  77751. BABYLON.serialize()
  77752. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  77753. __decorate([
  77754. BABYLON.serialize()
  77755. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  77756. __decorate([
  77757. BABYLON.serialize()
  77758. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  77759. __decorate([
  77760. BABYLON.serializeAsColor4()
  77761. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  77762. __decorate([
  77763. BABYLON.serialize()
  77764. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  77765. __decorate([
  77766. BABYLON.serialize()
  77767. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  77768. __decorate([
  77769. BABYLON.serialize()
  77770. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  77771. __decorate([
  77772. BABYLON.serialize()
  77773. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  77774. __decorate([
  77775. BABYLON.serialize()
  77776. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  77777. return ImageProcessingConfiguration;
  77778. }());
  77779. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  77780. })(BABYLON || (BABYLON = {}));
  77781. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  77782. var BABYLON;
  77783. (function (BABYLON) {
  77784. /**
  77785. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  77786. * It can help converting any input color in a desired output one. This can then be used to create effects
  77787. * from sepia, black and white to sixties or futuristic rendering...
  77788. *
  77789. * The only supported format is currently 3dl.
  77790. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  77791. */
  77792. var ColorGradingTexture = /** @class */ (function (_super) {
  77793. __extends(ColorGradingTexture, _super);
  77794. /**
  77795. * Instantiates a ColorGradingTexture from the following parameters.
  77796. *
  77797. * @param url The location of the color gradind data (currently only supporting 3dl)
  77798. * @param scene The scene the texture will be used in
  77799. */
  77800. function ColorGradingTexture(url, scene) {
  77801. var _this = _super.call(this, scene) || this;
  77802. if (!url) {
  77803. return _this;
  77804. }
  77805. _this._engine = scene.getEngine();
  77806. _this._textureMatrix = BABYLON.Matrix.Identity();
  77807. _this.name = url;
  77808. _this.url = url;
  77809. _this.hasAlpha = false;
  77810. _this.isCube = false;
  77811. _this.is3D = _this._engine.webGLVersion > 1;
  77812. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77813. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77814. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77815. _this.anisotropicFilteringLevel = 1;
  77816. _this._texture = _this._getFromCache(url, true);
  77817. if (!_this._texture) {
  77818. if (!scene.useDelayedTextureLoading) {
  77819. _this.loadTexture();
  77820. }
  77821. else {
  77822. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77823. }
  77824. }
  77825. return _this;
  77826. }
  77827. /**
  77828. * Returns the texture matrix used in most of the material.
  77829. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  77830. */
  77831. ColorGradingTexture.prototype.getTextureMatrix = function () {
  77832. return this._textureMatrix;
  77833. };
  77834. /**
  77835. * Occurs when the file being loaded is a .3dl LUT file.
  77836. */
  77837. ColorGradingTexture.prototype.load3dlTexture = function () {
  77838. var engine = this._engine;
  77839. var texture;
  77840. if (engine.webGLVersion === 1) {
  77841. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77842. }
  77843. else {
  77844. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77845. }
  77846. this._texture = texture;
  77847. var callback = function (text) {
  77848. if (typeof text !== "string") {
  77849. return;
  77850. }
  77851. var data = null;
  77852. var tempData = null;
  77853. var line;
  77854. var lines = text.split('\n');
  77855. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  77856. var maxColor = 0;
  77857. for (var i = 0; i < lines.length; i++) {
  77858. line = lines[i];
  77859. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  77860. continue;
  77861. if (line.indexOf('#') === 0)
  77862. continue;
  77863. var words = line.split(" ");
  77864. if (size === 0) {
  77865. // Number of space + one
  77866. size = words.length;
  77867. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  77868. tempData = new Float32Array(size * size * size * 4);
  77869. continue;
  77870. }
  77871. if (size != 0) {
  77872. var r = Math.max(parseInt(words[0]), 0);
  77873. var g = Math.max(parseInt(words[1]), 0);
  77874. var b = Math.max(parseInt(words[2]), 0);
  77875. maxColor = Math.max(r, maxColor);
  77876. maxColor = Math.max(g, maxColor);
  77877. maxColor = Math.max(b, maxColor);
  77878. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  77879. if (tempData) {
  77880. tempData[pixelStorageIndex + 0] = r;
  77881. tempData[pixelStorageIndex + 1] = g;
  77882. tempData[pixelStorageIndex + 2] = b;
  77883. }
  77884. pixelIndexSlice++;
  77885. if (pixelIndexSlice % size == 0) {
  77886. pixelIndexH++;
  77887. pixelIndexSlice = 0;
  77888. if (pixelIndexH % size == 0) {
  77889. pixelIndexW++;
  77890. pixelIndexH = 0;
  77891. }
  77892. }
  77893. }
  77894. }
  77895. if (tempData && data) {
  77896. for (var i = 0; i < tempData.length; i++) {
  77897. if (i > 0 && (i + 1) % 4 === 0) {
  77898. data[i] = 255;
  77899. }
  77900. else {
  77901. var value = tempData[i];
  77902. data[i] = (value / maxColor * 255);
  77903. }
  77904. }
  77905. }
  77906. if (texture.is3D) {
  77907. texture.updateSize(size, size, size);
  77908. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77909. }
  77910. else {
  77911. texture.updateSize(size * size, size);
  77912. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77913. }
  77914. };
  77915. var scene = this.getScene();
  77916. if (scene) {
  77917. scene._loadFile(this.url, callback);
  77918. }
  77919. else {
  77920. this._engine._loadFile(this.url, callback);
  77921. }
  77922. return this._texture;
  77923. };
  77924. /**
  77925. * Starts the loading process of the texture.
  77926. */
  77927. ColorGradingTexture.prototype.loadTexture = function () {
  77928. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  77929. this.load3dlTexture();
  77930. }
  77931. };
  77932. /**
  77933. * Clones the color gradind texture.
  77934. */
  77935. ColorGradingTexture.prototype.clone = function () {
  77936. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  77937. // Base texture
  77938. newTexture.level = this.level;
  77939. return newTexture;
  77940. };
  77941. /**
  77942. * Called during delayed load for textures.
  77943. */
  77944. ColorGradingTexture.prototype.delayLoad = function () {
  77945. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  77946. return;
  77947. }
  77948. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  77949. this._texture = this._getFromCache(this.url, true);
  77950. if (!this._texture) {
  77951. this.loadTexture();
  77952. }
  77953. };
  77954. /**
  77955. * Parses a color grading texture serialized by Babylon.
  77956. * @param parsedTexture The texture information being parsedTexture
  77957. * @param scene The scene to load the texture in
  77958. * @param rootUrl The root url of the data assets to load
  77959. * @return A color gradind texture
  77960. */
  77961. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  77962. var texture = null;
  77963. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  77964. texture = new ColorGradingTexture(parsedTexture.name, scene);
  77965. texture.name = parsedTexture.name;
  77966. texture.level = parsedTexture.level;
  77967. }
  77968. return texture;
  77969. };
  77970. /**
  77971. * Serializes the LUT texture to json format.
  77972. */
  77973. ColorGradingTexture.prototype.serialize = function () {
  77974. if (!this.name) {
  77975. return null;
  77976. }
  77977. var serializationObject = {};
  77978. serializationObject.name = this.name;
  77979. serializationObject.level = this.level;
  77980. serializationObject.customType = "BABYLON.ColorGradingTexture";
  77981. return serializationObject;
  77982. };
  77983. /**
  77984. * Empty line regex stored for GC.
  77985. */
  77986. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  77987. return ColorGradingTexture;
  77988. }(BABYLON.BaseTexture));
  77989. BABYLON.ColorGradingTexture = ColorGradingTexture;
  77990. })(BABYLON || (BABYLON = {}));
  77991. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  77992. var BABYLON;
  77993. (function (BABYLON) {
  77994. /**
  77995. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77996. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77997. * 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;
  77998. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77999. */
  78000. var ColorCurves = /** @class */ (function () {
  78001. function ColorCurves() {
  78002. this._dirty = true;
  78003. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  78004. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  78005. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  78006. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  78007. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  78008. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  78009. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  78010. this._globalHue = 30;
  78011. this._globalDensity = 0;
  78012. this._globalSaturation = 0;
  78013. this._globalExposure = 0;
  78014. this._highlightsHue = 30;
  78015. this._highlightsDensity = 0;
  78016. this._highlightsSaturation = 0;
  78017. this._highlightsExposure = 0;
  78018. this._midtonesHue = 30;
  78019. this._midtonesDensity = 0;
  78020. this._midtonesSaturation = 0;
  78021. this._midtonesExposure = 0;
  78022. this._shadowsHue = 30;
  78023. this._shadowsDensity = 0;
  78024. this._shadowsSaturation = 0;
  78025. this._shadowsExposure = 0;
  78026. }
  78027. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  78028. /**
  78029. * Gets the global Hue value.
  78030. * 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).
  78031. */
  78032. get: function () {
  78033. return this._globalHue;
  78034. },
  78035. /**
  78036. * Sets the global Hue value.
  78037. * 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).
  78038. */
  78039. set: function (value) {
  78040. this._globalHue = value;
  78041. this._dirty = true;
  78042. },
  78043. enumerable: true,
  78044. configurable: true
  78045. });
  78046. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  78047. /**
  78048. * Gets the global Density value.
  78049. * 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.
  78050. * Values less than zero provide a filter of opposite hue.
  78051. */
  78052. get: function () {
  78053. return this._globalDensity;
  78054. },
  78055. /**
  78056. * Sets the global Density value.
  78057. * 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.
  78058. * Values less than zero provide a filter of opposite hue.
  78059. */
  78060. set: function (value) {
  78061. this._globalDensity = value;
  78062. this._dirty = true;
  78063. },
  78064. enumerable: true,
  78065. configurable: true
  78066. });
  78067. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  78068. /**
  78069. * Gets the global Saturation value.
  78070. * 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.
  78071. */
  78072. get: function () {
  78073. return this._globalSaturation;
  78074. },
  78075. /**
  78076. * Sets the global Saturation value.
  78077. * 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.
  78078. */
  78079. set: function (value) {
  78080. this._globalSaturation = value;
  78081. this._dirty = true;
  78082. },
  78083. enumerable: true,
  78084. configurable: true
  78085. });
  78086. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  78087. /**
  78088. * Gets the global Exposure value.
  78089. * 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.
  78090. */
  78091. get: function () {
  78092. return this._globalExposure;
  78093. },
  78094. /**
  78095. * Sets the global Exposure value.
  78096. * 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.
  78097. */
  78098. set: function (value) {
  78099. this._globalExposure = value;
  78100. this._dirty = true;
  78101. },
  78102. enumerable: true,
  78103. configurable: true
  78104. });
  78105. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  78106. /**
  78107. * Gets the highlights Hue value.
  78108. * 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).
  78109. */
  78110. get: function () {
  78111. return this._highlightsHue;
  78112. },
  78113. /**
  78114. * Sets the highlights Hue value.
  78115. * 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).
  78116. */
  78117. set: function (value) {
  78118. this._highlightsHue = value;
  78119. this._dirty = true;
  78120. },
  78121. enumerable: true,
  78122. configurable: true
  78123. });
  78124. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  78125. /**
  78126. * Gets the highlights Density value.
  78127. * 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.
  78128. * Values less than zero provide a filter of opposite hue.
  78129. */
  78130. get: function () {
  78131. return this._highlightsDensity;
  78132. },
  78133. /**
  78134. * Sets the highlights Density value.
  78135. * 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.
  78136. * Values less than zero provide a filter of opposite hue.
  78137. */
  78138. set: function (value) {
  78139. this._highlightsDensity = value;
  78140. this._dirty = true;
  78141. },
  78142. enumerable: true,
  78143. configurable: true
  78144. });
  78145. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  78146. /**
  78147. * Gets the highlights Saturation value.
  78148. * 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.
  78149. */
  78150. get: function () {
  78151. return this._highlightsSaturation;
  78152. },
  78153. /**
  78154. * Sets the highlights Saturation value.
  78155. * 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.
  78156. */
  78157. set: function (value) {
  78158. this._highlightsSaturation = value;
  78159. this._dirty = true;
  78160. },
  78161. enumerable: true,
  78162. configurable: true
  78163. });
  78164. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  78165. /**
  78166. * Gets the highlights Exposure value.
  78167. * 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.
  78168. */
  78169. get: function () {
  78170. return this._highlightsExposure;
  78171. },
  78172. /**
  78173. * Sets the highlights Exposure value.
  78174. * 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.
  78175. */
  78176. set: function (value) {
  78177. this._highlightsExposure = value;
  78178. this._dirty = true;
  78179. },
  78180. enumerable: true,
  78181. configurable: true
  78182. });
  78183. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  78184. /**
  78185. * Gets the midtones Hue value.
  78186. * 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).
  78187. */
  78188. get: function () {
  78189. return this._midtonesHue;
  78190. },
  78191. /**
  78192. * Sets the midtones Hue value.
  78193. * 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).
  78194. */
  78195. set: function (value) {
  78196. this._midtonesHue = value;
  78197. this._dirty = true;
  78198. },
  78199. enumerable: true,
  78200. configurable: true
  78201. });
  78202. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  78203. /**
  78204. * Gets the midtones Density value.
  78205. * 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.
  78206. * Values less than zero provide a filter of opposite hue.
  78207. */
  78208. get: function () {
  78209. return this._midtonesDensity;
  78210. },
  78211. /**
  78212. * Sets the midtones Density value.
  78213. * 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.
  78214. * Values less than zero provide a filter of opposite hue.
  78215. */
  78216. set: function (value) {
  78217. this._midtonesDensity = value;
  78218. this._dirty = true;
  78219. },
  78220. enumerable: true,
  78221. configurable: true
  78222. });
  78223. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  78224. /**
  78225. * Gets the midtones Saturation value.
  78226. * 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.
  78227. */
  78228. get: function () {
  78229. return this._midtonesSaturation;
  78230. },
  78231. /**
  78232. * Sets the midtones Saturation value.
  78233. * 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.
  78234. */
  78235. set: function (value) {
  78236. this._midtonesSaturation = value;
  78237. this._dirty = true;
  78238. },
  78239. enumerable: true,
  78240. configurable: true
  78241. });
  78242. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  78243. /**
  78244. * Gets the midtones Exposure value.
  78245. * 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.
  78246. */
  78247. get: function () {
  78248. return this._midtonesExposure;
  78249. },
  78250. /**
  78251. * Sets the midtones Exposure value.
  78252. * 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.
  78253. */
  78254. set: function (value) {
  78255. this._midtonesExposure = value;
  78256. this._dirty = true;
  78257. },
  78258. enumerable: true,
  78259. configurable: true
  78260. });
  78261. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  78262. /**
  78263. * Gets the shadows Hue value.
  78264. * 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).
  78265. */
  78266. get: function () {
  78267. return this._shadowsHue;
  78268. },
  78269. /**
  78270. * Sets the shadows Hue value.
  78271. * 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).
  78272. */
  78273. set: function (value) {
  78274. this._shadowsHue = value;
  78275. this._dirty = true;
  78276. },
  78277. enumerable: true,
  78278. configurable: true
  78279. });
  78280. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  78281. /**
  78282. * Gets the shadows Density value.
  78283. * 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.
  78284. * Values less than zero provide a filter of opposite hue.
  78285. */
  78286. get: function () {
  78287. return this._shadowsDensity;
  78288. },
  78289. /**
  78290. * Sets the shadows Density value.
  78291. * 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.
  78292. * Values less than zero provide a filter of opposite hue.
  78293. */
  78294. set: function (value) {
  78295. this._shadowsDensity = value;
  78296. this._dirty = true;
  78297. },
  78298. enumerable: true,
  78299. configurable: true
  78300. });
  78301. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  78302. /**
  78303. * Gets the shadows Saturation value.
  78304. * 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.
  78305. */
  78306. get: function () {
  78307. return this._shadowsSaturation;
  78308. },
  78309. /**
  78310. * Sets the shadows Saturation value.
  78311. * 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.
  78312. */
  78313. set: function (value) {
  78314. this._shadowsSaturation = value;
  78315. this._dirty = true;
  78316. },
  78317. enumerable: true,
  78318. configurable: true
  78319. });
  78320. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  78321. /**
  78322. * Gets the shadows Exposure value.
  78323. * 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.
  78324. */
  78325. get: function () {
  78326. return this._shadowsExposure;
  78327. },
  78328. /**
  78329. * Sets the shadows Exposure value.
  78330. * 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.
  78331. */
  78332. set: function (value) {
  78333. this._shadowsExposure = value;
  78334. this._dirty = true;
  78335. },
  78336. enumerable: true,
  78337. configurable: true
  78338. });
  78339. ColorCurves.prototype.getClassName = function () {
  78340. return "ColorCurves";
  78341. };
  78342. /**
  78343. * Binds the color curves to the shader.
  78344. * @param colorCurves The color curve to bind
  78345. * @param effect The effect to bind to
  78346. */
  78347. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  78348. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  78349. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  78350. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  78351. if (colorCurves._dirty) {
  78352. colorCurves._dirty = false;
  78353. // Fill in global info.
  78354. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  78355. // Compute highlights info.
  78356. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  78357. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  78358. // Compute midtones info.
  78359. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  78360. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  78361. // Compute shadows info.
  78362. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  78363. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  78364. // Compute deltas (neutral is midtones).
  78365. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  78366. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  78367. }
  78368. if (effect) {
  78369. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  78370. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  78371. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  78372. }
  78373. };
  78374. /**
  78375. * Prepare the list of uniforms associated with the ColorCurves effects.
  78376. * @param uniformsList The list of uniforms used in the effect
  78377. */
  78378. ColorCurves.PrepareUniforms = function (uniformsList) {
  78379. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  78380. };
  78381. /**
  78382. * Returns color grading data based on a hue, density, saturation and exposure value.
  78383. * @param filterHue The hue of the color filter.
  78384. * @param filterDensity The density of the color filter.
  78385. * @param saturation The saturation.
  78386. * @param exposure The exposure.
  78387. * @param result The result data container.
  78388. */
  78389. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  78390. if (hue == null) {
  78391. return;
  78392. }
  78393. hue = ColorCurves.clamp(hue, 0, 360);
  78394. density = ColorCurves.clamp(density, -100, 100);
  78395. saturation = ColorCurves.clamp(saturation, -100, 100);
  78396. exposure = ColorCurves.clamp(exposure, -100, 100);
  78397. // Remap the slider/config filter density with non-linear mapping and also scale by half
  78398. // so that the maximum filter density is only 50% control. This provides fine control
  78399. // for small values and reasonable range.
  78400. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  78401. density *= 0.5;
  78402. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  78403. if (density < 0) {
  78404. density *= -1;
  78405. hue = (hue + 180) % 360;
  78406. }
  78407. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  78408. result.scaleToRef(2, result);
  78409. result.a = 1 + 0.01 * saturation;
  78410. };
  78411. /**
  78412. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  78413. * @param value The input slider value in range [-100,100].
  78414. * @returns Adjusted value.
  78415. */
  78416. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  78417. value /= 100;
  78418. var x = Math.abs(value);
  78419. x = Math.pow(x, 2);
  78420. if (value < 0) {
  78421. x *= -1;
  78422. }
  78423. x *= 100;
  78424. return x;
  78425. };
  78426. /**
  78427. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  78428. * @param hue The hue (H) input.
  78429. * @param saturation The saturation (S) input.
  78430. * @param brightness The brightness (B) input.
  78431. * @result An RGBA color represented as Vector4.
  78432. */
  78433. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  78434. var h = ColorCurves.clamp(hue, 0, 360);
  78435. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  78436. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  78437. if (s === 0) {
  78438. result.r = v;
  78439. result.g = v;
  78440. result.b = v;
  78441. }
  78442. else {
  78443. // sector 0 to 5
  78444. h /= 60;
  78445. var i = Math.floor(h);
  78446. // fractional part of h
  78447. var f = h - i;
  78448. var p = v * (1 - s);
  78449. var q = v * (1 - s * f);
  78450. var t = v * (1 - s * (1 - f));
  78451. switch (i) {
  78452. case 0:
  78453. result.r = v;
  78454. result.g = t;
  78455. result.b = p;
  78456. break;
  78457. case 1:
  78458. result.r = q;
  78459. result.g = v;
  78460. result.b = p;
  78461. break;
  78462. case 2:
  78463. result.r = p;
  78464. result.g = v;
  78465. result.b = t;
  78466. break;
  78467. case 3:
  78468. result.r = p;
  78469. result.g = q;
  78470. result.b = v;
  78471. break;
  78472. case 4:
  78473. result.r = t;
  78474. result.g = p;
  78475. result.b = v;
  78476. break;
  78477. default: // case 5:
  78478. result.r = v;
  78479. result.g = p;
  78480. result.b = q;
  78481. break;
  78482. }
  78483. }
  78484. result.a = 1;
  78485. };
  78486. /**
  78487. * Returns a value clamped between min and max
  78488. * @param value The value to clamp
  78489. * @param min The minimum of value
  78490. * @param max The maximum of value
  78491. * @returns The clamped value.
  78492. */
  78493. ColorCurves.clamp = function (value, min, max) {
  78494. return Math.min(Math.max(value, min), max);
  78495. };
  78496. /**
  78497. * Clones the current color curve instance.
  78498. * @return The cloned curves
  78499. */
  78500. ColorCurves.prototype.clone = function () {
  78501. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  78502. };
  78503. /**
  78504. * Serializes the current color curve instance to a json representation.
  78505. * @return a JSON representation
  78506. */
  78507. ColorCurves.prototype.serialize = function () {
  78508. return BABYLON.SerializationHelper.Serialize(this);
  78509. };
  78510. /**
  78511. * Parses the color curve from a json representation.
  78512. * @param source the JSON source to parse
  78513. * @return The parsed curves
  78514. */
  78515. ColorCurves.Parse = function (source) {
  78516. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  78517. };
  78518. __decorate([
  78519. BABYLON.serialize()
  78520. ], ColorCurves.prototype, "_globalHue", void 0);
  78521. __decorate([
  78522. BABYLON.serialize()
  78523. ], ColorCurves.prototype, "_globalDensity", void 0);
  78524. __decorate([
  78525. BABYLON.serialize()
  78526. ], ColorCurves.prototype, "_globalSaturation", void 0);
  78527. __decorate([
  78528. BABYLON.serialize()
  78529. ], ColorCurves.prototype, "_globalExposure", void 0);
  78530. __decorate([
  78531. BABYLON.serialize()
  78532. ], ColorCurves.prototype, "_highlightsHue", void 0);
  78533. __decorate([
  78534. BABYLON.serialize()
  78535. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  78536. __decorate([
  78537. BABYLON.serialize()
  78538. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  78539. __decorate([
  78540. BABYLON.serialize()
  78541. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  78542. __decorate([
  78543. BABYLON.serialize()
  78544. ], ColorCurves.prototype, "_midtonesHue", void 0);
  78545. __decorate([
  78546. BABYLON.serialize()
  78547. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  78548. __decorate([
  78549. BABYLON.serialize()
  78550. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  78551. __decorate([
  78552. BABYLON.serialize()
  78553. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  78554. return ColorCurves;
  78555. }());
  78556. BABYLON.ColorCurves = ColorCurves;
  78557. })(BABYLON || (BABYLON = {}));
  78558. //# sourceMappingURL=babylon.colorCurves.js.map
  78559. var BABYLON;
  78560. (function (BABYLON) {
  78561. var RefractionPostProcess = /** @class */ (function (_super) {
  78562. __extends(RefractionPostProcess, _super);
  78563. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  78564. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  78565. _this.color = color;
  78566. _this.depth = depth;
  78567. _this.colorLevel = colorLevel;
  78568. _this._ownRefractionTexture = true;
  78569. _this.onActivateObservable.add(function (cam) {
  78570. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  78571. });
  78572. _this.onApplyObservable.add(function (effect) {
  78573. effect.setColor3("baseColor", _this.color);
  78574. effect.setFloat("depth", _this.depth);
  78575. effect.setFloat("colorLevel", _this.colorLevel);
  78576. effect.setTexture("refractionSampler", _this._refTexture);
  78577. });
  78578. return _this;
  78579. }
  78580. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  78581. /**
  78582. * Gets or sets the refraction texture
  78583. * Please note that you are responsible for disposing the texture if you set it manually
  78584. */
  78585. get: function () {
  78586. return this._refTexture;
  78587. },
  78588. set: function (value) {
  78589. if (this._refTexture && this._ownRefractionTexture) {
  78590. this._refTexture.dispose();
  78591. }
  78592. this._refTexture = value;
  78593. this._ownRefractionTexture = false;
  78594. },
  78595. enumerable: true,
  78596. configurable: true
  78597. });
  78598. // Methods
  78599. RefractionPostProcess.prototype.dispose = function (camera) {
  78600. if (this._refTexture && this._ownRefractionTexture) {
  78601. this._refTexture.dispose();
  78602. this._refTexture = null;
  78603. }
  78604. _super.prototype.dispose.call(this, camera);
  78605. };
  78606. return RefractionPostProcess;
  78607. }(BABYLON.PostProcess));
  78608. BABYLON.RefractionPostProcess = RefractionPostProcess;
  78609. })(BABYLON || (BABYLON = {}));
  78610. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  78611. var BABYLON;
  78612. (function (BABYLON) {
  78613. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  78614. __extends(BlackAndWhitePostProcess, _super);
  78615. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  78616. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  78617. _this.degree = 1;
  78618. _this.onApplyObservable.add(function (effect) {
  78619. effect.setFloat("degree", _this.degree);
  78620. });
  78621. return _this;
  78622. }
  78623. return BlackAndWhitePostProcess;
  78624. }(BABYLON.PostProcess));
  78625. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  78626. })(BABYLON || (BABYLON = {}));
  78627. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  78628. var BABYLON;
  78629. (function (BABYLON) {
  78630. /**
  78631. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  78632. * input texture to perform effects such as edge detection or sharpening
  78633. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78634. */
  78635. var ConvolutionPostProcess = /** @class */ (function (_super) {
  78636. __extends(ConvolutionPostProcess, _super);
  78637. /**
  78638. * Creates a new instance ConvolutionPostProcess
  78639. * @param name The name of the effect.
  78640. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  78641. * @param options The required width/height ratio to downsize to before computing the render pass.
  78642. * @param camera The camera to apply the render pass to.
  78643. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78644. * @param engine The engine which the post process will be applied. (default: current engine)
  78645. * @param reusable If the post process can be reused on the same frame. (default: false)
  78646. * @param textureType Type of textures used when performing the post process. (default: 0)
  78647. */
  78648. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  78649. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78650. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78651. _this.kernel = kernel;
  78652. _this.onApply = function (effect) {
  78653. effect.setFloat2("screenSize", _this.width, _this.height);
  78654. effect.setArray("kernel", _this.kernel);
  78655. };
  78656. return _this;
  78657. }
  78658. // Statics
  78659. /**
  78660. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78661. */
  78662. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  78663. /**
  78664. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78665. */
  78666. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  78667. /**
  78668. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78669. */
  78670. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  78671. /**
  78672. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78673. */
  78674. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  78675. /**
  78676. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78677. */
  78678. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  78679. /**
  78680. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78681. */
  78682. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  78683. return ConvolutionPostProcess;
  78684. }(BABYLON.PostProcess));
  78685. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  78686. })(BABYLON || (BABYLON = {}));
  78687. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  78688. var BABYLON;
  78689. (function (BABYLON) {
  78690. var FilterPostProcess = /** @class */ (function (_super) {
  78691. __extends(FilterPostProcess, _super);
  78692. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  78693. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  78694. _this.kernelMatrix = kernelMatrix;
  78695. _this.onApply = function (effect) {
  78696. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  78697. };
  78698. return _this;
  78699. }
  78700. return FilterPostProcess;
  78701. }(BABYLON.PostProcess));
  78702. BABYLON.FilterPostProcess = FilterPostProcess;
  78703. })(BABYLON || (BABYLON = {}));
  78704. //# sourceMappingURL=babylon.filterPostProcess.js.map
  78705. var BABYLON;
  78706. (function (BABYLON) {
  78707. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  78708. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  78709. __extends(VolumetricLightScatteringPostProcess, _super);
  78710. /**
  78711. * @constructor
  78712. * @param {string} name - The post-process name
  78713. * @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)
  78714. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  78715. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  78716. * @param {number} samples - The post-process quality, default 100
  78717. * @param {number} samplingMode - The post-process filtering mode
  78718. * @param {BABYLON.Engine} engine - The babylon engine
  78719. * @param {boolean} reusable - If the post-process is reusable
  78720. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  78721. */
  78722. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  78723. if (samples === void 0) { samples = 100; }
  78724. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78725. 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;
  78726. _this._screenCoordinates = BABYLON.Vector2.Zero();
  78727. /**
  78728. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  78729. */
  78730. _this.customMeshPosition = BABYLON.Vector3.Zero();
  78731. /**
  78732. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  78733. */
  78734. _this.useCustomMeshPosition = false;
  78735. /**
  78736. * If the post-process should inverse the light scattering direction
  78737. */
  78738. _this.invert = true;
  78739. /**
  78740. * Array containing the excluded meshes not rendered in the internal pass
  78741. */
  78742. _this.excludedMeshes = new Array();
  78743. /**
  78744. * Controls the overall intensity of the post-process
  78745. */
  78746. _this.exposure = 0.3;
  78747. /**
  78748. * Dissipates each sample's contribution in range [0, 1]
  78749. */
  78750. _this.decay = 0.96815;
  78751. /**
  78752. * Controls the overall intensity of each sample
  78753. */
  78754. _this.weight = 0.58767;
  78755. /**
  78756. * Controls the density of each sample
  78757. */
  78758. _this.density = 0.926;
  78759. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  78760. engine = scene.getEngine();
  78761. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  78762. // Configure mesh
  78763. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  78764. // Configure
  78765. _this._createPass(scene, ratio.passRatio || ratio);
  78766. _this.onActivate = function (camera) {
  78767. if (!_this.isSupported) {
  78768. _this.dispose(camera);
  78769. }
  78770. _this.onActivate = null;
  78771. };
  78772. _this.onApplyObservable.add(function (effect) {
  78773. _this._updateMeshScreenCoordinates(scene);
  78774. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  78775. effect.setFloat("exposure", _this.exposure);
  78776. effect.setFloat("decay", _this.decay);
  78777. effect.setFloat("weight", _this.weight);
  78778. effect.setFloat("density", _this.density);
  78779. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  78780. });
  78781. return _this;
  78782. }
  78783. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  78784. get: function () {
  78785. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78786. return false;
  78787. },
  78788. set: function (useDiffuseColor) {
  78789. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78790. },
  78791. enumerable: true,
  78792. configurable: true
  78793. });
  78794. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  78795. return "VolumetricLightScatteringPostProcess";
  78796. };
  78797. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  78798. var mesh = subMesh.getMesh();
  78799. // Render this.mesh as default
  78800. if (mesh === this.mesh && mesh.material) {
  78801. return mesh.material.isReady(mesh);
  78802. }
  78803. var defines = [];
  78804. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78805. var material = subMesh.getMaterial();
  78806. // Alpha test
  78807. if (material) {
  78808. if (material.needAlphaTesting()) {
  78809. defines.push("#define ALPHATEST");
  78810. }
  78811. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78812. attribs.push(BABYLON.VertexBuffer.UVKind);
  78813. defines.push("#define UV1");
  78814. }
  78815. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78816. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78817. defines.push("#define UV2");
  78818. }
  78819. }
  78820. // Bones
  78821. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78822. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78823. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78824. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78825. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78826. }
  78827. else {
  78828. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78829. }
  78830. // Instances
  78831. if (useInstances) {
  78832. defines.push("#define INSTANCES");
  78833. attribs.push("world0");
  78834. attribs.push("world1");
  78835. attribs.push("world2");
  78836. attribs.push("world3");
  78837. }
  78838. // Get correct effect
  78839. var join = defines.join("\n");
  78840. if (this._cachedDefines !== join) {
  78841. this._cachedDefines = join;
  78842. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  78843. }
  78844. return this._volumetricLightScatteringPass.isReady();
  78845. };
  78846. /**
  78847. * Sets the new light position for light scattering effect
  78848. * @param {BABYLON.Vector3} The new custom light position
  78849. */
  78850. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  78851. this.customMeshPosition = position;
  78852. };
  78853. /**
  78854. * Returns the light position for light scattering effect
  78855. * @return {BABYLON.Vector3} The custom light position
  78856. */
  78857. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  78858. return this.customMeshPosition;
  78859. };
  78860. /**
  78861. * Disposes the internal assets and detaches the post-process from the camera
  78862. */
  78863. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  78864. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  78865. if (rttIndex !== -1) {
  78866. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  78867. }
  78868. this._volumetricLightScatteringRTT.dispose();
  78869. _super.prototype.dispose.call(this, camera);
  78870. };
  78871. /**
  78872. * Returns the render target texture used by the post-process
  78873. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  78874. */
  78875. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  78876. return this._volumetricLightScatteringRTT;
  78877. };
  78878. // Private methods
  78879. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  78880. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  78881. return true;
  78882. }
  78883. return false;
  78884. };
  78885. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  78886. var _this = this;
  78887. var engine = scene.getEngine();
  78888. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78889. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78890. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78891. this._volumetricLightScatteringRTT.renderList = null;
  78892. this._volumetricLightScatteringRTT.renderParticles = false;
  78893. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  78894. var camera = this.getCamera();
  78895. if (camera) {
  78896. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78897. }
  78898. else {
  78899. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78900. }
  78901. // Custom render function for submeshes
  78902. var renderSubMesh = function (subMesh) {
  78903. var mesh = subMesh.getRenderingMesh();
  78904. if (_this._meshExcluded(mesh)) {
  78905. return;
  78906. }
  78907. var material = subMesh.getMaterial();
  78908. if (!material) {
  78909. return;
  78910. }
  78911. var scene = mesh.getScene();
  78912. var engine = scene.getEngine();
  78913. // Culling
  78914. engine.setState(material.backFaceCulling);
  78915. // Managing instances
  78916. var batch = mesh._getInstancesRenderList(subMesh._id);
  78917. if (batch.mustReturn) {
  78918. return;
  78919. }
  78920. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78921. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  78922. var effect = _this._volumetricLightScatteringPass;
  78923. if (mesh === _this.mesh) {
  78924. if (subMesh.effect) {
  78925. effect = subMesh.effect;
  78926. }
  78927. else {
  78928. effect = material.getEffect();
  78929. }
  78930. }
  78931. engine.enableEffect(effect);
  78932. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  78933. if (mesh === _this.mesh) {
  78934. material.bind(mesh.getWorldMatrix(), mesh);
  78935. }
  78936. else {
  78937. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  78938. // Alpha test
  78939. if (material && material.needAlphaTesting()) {
  78940. var alphaTexture = material.getAlphaTestTexture();
  78941. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  78942. if (alphaTexture) {
  78943. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78944. }
  78945. }
  78946. // Bones
  78947. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78948. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78949. }
  78950. }
  78951. // Draw
  78952. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  78953. }
  78954. };
  78955. // Render target texture callbacks
  78956. var savedSceneClearColor;
  78957. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  78958. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  78959. savedSceneClearColor = scene.clearColor;
  78960. scene.clearColor = sceneClearColor;
  78961. });
  78962. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  78963. scene.clearColor = savedSceneClearColor;
  78964. });
  78965. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78966. var engine = scene.getEngine();
  78967. var index;
  78968. if (depthOnlySubMeshes.length) {
  78969. engine.setColorWrite(false);
  78970. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78971. renderSubMesh(depthOnlySubMeshes.data[index]);
  78972. }
  78973. engine.setColorWrite(true);
  78974. }
  78975. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78976. renderSubMesh(opaqueSubMeshes.data[index]);
  78977. }
  78978. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78979. renderSubMesh(alphaTestSubMeshes.data[index]);
  78980. }
  78981. if (transparentSubMeshes.length) {
  78982. // Sort sub meshes
  78983. for (index = 0; index < transparentSubMeshes.length; index++) {
  78984. var submesh = transparentSubMeshes.data[index];
  78985. var boundingInfo = submesh.getBoundingInfo();
  78986. if (boundingInfo && scene.activeCamera) {
  78987. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  78988. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  78989. }
  78990. }
  78991. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  78992. sortedArray.sort(function (a, b) {
  78993. // Alpha index first
  78994. if (a._alphaIndex > b._alphaIndex) {
  78995. return 1;
  78996. }
  78997. if (a._alphaIndex < b._alphaIndex) {
  78998. return -1;
  78999. }
  79000. // Then distance to camera
  79001. if (a._distanceToCamera < b._distanceToCamera) {
  79002. return 1;
  79003. }
  79004. if (a._distanceToCamera > b._distanceToCamera) {
  79005. return -1;
  79006. }
  79007. return 0;
  79008. });
  79009. // Render sub meshes
  79010. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  79011. for (index = 0; index < sortedArray.length; index++) {
  79012. renderSubMesh(sortedArray[index]);
  79013. }
  79014. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  79015. }
  79016. };
  79017. };
  79018. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  79019. var transform = scene.getTransformMatrix();
  79020. var meshPosition;
  79021. if (this.useCustomMeshPosition) {
  79022. meshPosition = this.customMeshPosition;
  79023. }
  79024. else if (this.attachedNode) {
  79025. meshPosition = this.attachedNode.position;
  79026. }
  79027. else {
  79028. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  79029. }
  79030. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  79031. this._screenCoordinates.x = pos.x / this._viewPort.width;
  79032. this._screenCoordinates.y = pos.y / this._viewPort.height;
  79033. if (this.invert)
  79034. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  79035. };
  79036. // Static methods
  79037. /**
  79038. * Creates a default mesh for the Volumeric Light Scattering post-process
  79039. * @param {string} The mesh name
  79040. * @param {BABYLON.Scene} The scene where to create the mesh
  79041. * @return {BABYLON.Mesh} the default mesh
  79042. */
  79043. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  79044. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  79045. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  79046. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  79047. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  79048. mesh.material = material;
  79049. return mesh;
  79050. };
  79051. __decorate([
  79052. BABYLON.serializeAsVector3()
  79053. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  79054. __decorate([
  79055. BABYLON.serialize()
  79056. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  79057. __decorate([
  79058. BABYLON.serialize()
  79059. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  79060. __decorate([
  79061. BABYLON.serializeAsMeshReference()
  79062. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  79063. __decorate([
  79064. BABYLON.serialize()
  79065. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  79066. __decorate([
  79067. BABYLON.serialize()
  79068. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  79069. __decorate([
  79070. BABYLON.serialize()
  79071. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  79072. __decorate([
  79073. BABYLON.serialize()
  79074. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  79075. __decorate([
  79076. BABYLON.serialize()
  79077. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  79078. return VolumetricLightScatteringPostProcess;
  79079. }(BABYLON.PostProcess));
  79080. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  79081. })(BABYLON || (BABYLON = {}));
  79082. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  79083. //
  79084. // This post-process allows the modification of rendered colors by using
  79085. // a 'look-up table' (LUT). This effect is also called Color Grading.
  79086. //
  79087. // The object needs to be provided an url to a texture containing the color
  79088. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  79089. // Use an image editing software to tweak the LUT to match your needs.
  79090. //
  79091. // For an example of a color LUT, see here:
  79092. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  79093. // For explanations on color grading, see here:
  79094. // http://udn.epicgames.com/Three/ColorGrading.html
  79095. //
  79096. var BABYLON;
  79097. (function (BABYLON) {
  79098. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  79099. __extends(ColorCorrectionPostProcess, _super);
  79100. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  79101. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  79102. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  79103. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  79104. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79105. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79106. _this.onApply = function (effect) {
  79107. effect.setTexture("colorTable", _this._colorTableTexture);
  79108. };
  79109. return _this;
  79110. }
  79111. return ColorCorrectionPostProcess;
  79112. }(BABYLON.PostProcess));
  79113. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  79114. })(BABYLON || (BABYLON = {}));
  79115. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  79116. var BABYLON;
  79117. (function (BABYLON) {
  79118. /** Defines operator used for tonemapping */
  79119. var TonemappingOperator;
  79120. (function (TonemappingOperator) {
  79121. /** Hable */
  79122. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  79123. /** Reinhard */
  79124. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  79125. /** HejiDawson */
  79126. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  79127. /** Photographic */
  79128. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  79129. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  79130. ;
  79131. /**
  79132. * Defines a post process to apply tone mapping
  79133. */
  79134. var TonemapPostProcess = /** @class */ (function (_super) {
  79135. __extends(TonemapPostProcess, _super);
  79136. /**
  79137. * Creates a new TonemapPostProcess
  79138. * @param name defines the name of the postprocess
  79139. * @param _operator defines the operator to use
  79140. * @param exposureAdjustment defines the required exposure adjustement
  79141. * @param camera defines the camera to use (can be null)
  79142. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  79143. * @param engine defines the hosting engine (can be ignore if camera is set)
  79144. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  79145. */
  79146. function TonemapPostProcess(name, _operator,
  79147. /** Defines the required exposure adjustement */
  79148. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  79149. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79150. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79151. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  79152. _this._operator = _operator;
  79153. _this.exposureAdjustment = exposureAdjustment;
  79154. var defines = "#define ";
  79155. if (_this._operator === TonemappingOperator.Hable)
  79156. defines += "HABLE_TONEMAPPING";
  79157. else if (_this._operator === TonemappingOperator.Reinhard)
  79158. defines += "REINHARD_TONEMAPPING";
  79159. else if (_this._operator === TonemappingOperator.HejiDawson)
  79160. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  79161. else if (_this._operator === TonemappingOperator.Photographic)
  79162. defines += "PHOTOGRAPHIC_TONEMAPPING";
  79163. //sadly a second call to create the effect.
  79164. _this.updateEffect(defines);
  79165. _this.onApply = function (effect) {
  79166. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  79167. };
  79168. return _this;
  79169. }
  79170. return TonemapPostProcess;
  79171. }(BABYLON.PostProcess));
  79172. BABYLON.TonemapPostProcess = TonemapPostProcess;
  79173. })(BABYLON || (BABYLON = {}));
  79174. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  79175. var BABYLON;
  79176. (function (BABYLON) {
  79177. var DisplayPassPostProcess = /** @class */ (function (_super) {
  79178. __extends(DisplayPassPostProcess, _super);
  79179. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  79180. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  79181. }
  79182. return DisplayPassPostProcess;
  79183. }(BABYLON.PostProcess));
  79184. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  79185. })(BABYLON || (BABYLON = {}));
  79186. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  79187. var BABYLON;
  79188. (function (BABYLON) {
  79189. var HighlightsPostProcess = /** @class */ (function (_super) {
  79190. __extends(HighlightsPostProcess, _super);
  79191. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  79192. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79193. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  79194. }
  79195. return HighlightsPostProcess;
  79196. }(BABYLON.PostProcess));
  79197. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  79198. })(BABYLON || (BABYLON = {}));
  79199. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  79200. var BABYLON;
  79201. (function (BABYLON) {
  79202. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  79203. __extends(ImageProcessingPostProcess, _super);
  79204. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  79205. if (camera === void 0) { camera = null; }
  79206. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79207. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  79208. _this._fromLinearSpace = true;
  79209. /**
  79210. * Defines cache preventing GC.
  79211. */
  79212. _this._defines = {
  79213. IMAGEPROCESSING: false,
  79214. VIGNETTE: false,
  79215. VIGNETTEBLENDMODEMULTIPLY: false,
  79216. VIGNETTEBLENDMODEOPAQUE: false,
  79217. TONEMAPPING: false,
  79218. CONTRAST: false,
  79219. COLORCURVES: false,
  79220. COLORGRADING: false,
  79221. COLORGRADING3D: false,
  79222. FROMLINEARSPACE: false,
  79223. SAMPLER3DGREENDEPTH: false,
  79224. SAMPLER3DBGRMAP: false,
  79225. IMAGEPROCESSINGPOSTPROCESS: false,
  79226. EXPOSURE: false,
  79227. };
  79228. // Setup the configuration as forced by the constructor. This would then not force the
  79229. // scene materials output in linear space and let untouched the default forward pass.
  79230. if (imageProcessingConfiguration) {
  79231. imageProcessingConfiguration.applyByPostProcess = true;
  79232. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  79233. // This will cause the shader to be compiled
  79234. _this.fromLinearSpace = false;
  79235. }
  79236. // Setup the default processing configuration to the scene.
  79237. else {
  79238. _this._attachImageProcessingConfiguration(null, true);
  79239. _this.imageProcessingConfiguration.applyByPostProcess = true;
  79240. }
  79241. _this.onApply = function (effect) {
  79242. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  79243. };
  79244. return _this;
  79245. }
  79246. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  79247. /**
  79248. * Gets the image processing configuration used either in this material.
  79249. */
  79250. get: function () {
  79251. return this._imageProcessingConfiguration;
  79252. },
  79253. /**
  79254. * Sets the Default image processing configuration used either in the this material.
  79255. *
  79256. * If sets to null, the scene one is in use.
  79257. */
  79258. set: function (value) {
  79259. this._attachImageProcessingConfiguration(value);
  79260. },
  79261. enumerable: true,
  79262. configurable: true
  79263. });
  79264. /**
  79265. * Attaches a new image processing configuration to the PBR Material.
  79266. * @param configuration
  79267. */
  79268. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  79269. var _this = this;
  79270. if (doNotBuild === void 0) { doNotBuild = false; }
  79271. if (configuration === this._imageProcessingConfiguration) {
  79272. return;
  79273. }
  79274. // Detaches observer.
  79275. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79276. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79277. }
  79278. // Pick the scene configuration if needed.
  79279. if (!configuration) {
  79280. var scene = null;
  79281. var engine = this.getEngine();
  79282. var camera = this.getCamera();
  79283. if (camera) {
  79284. scene = camera.getScene();
  79285. }
  79286. else if (engine && engine.scenes) {
  79287. var scenes = engine.scenes;
  79288. scene = scenes[scenes.length - 1];
  79289. }
  79290. else {
  79291. scene = BABYLON.Engine.LastCreatedScene;
  79292. }
  79293. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  79294. }
  79295. else {
  79296. this._imageProcessingConfiguration = configuration;
  79297. }
  79298. // Attaches observer.
  79299. if (this._imageProcessingConfiguration) {
  79300. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  79301. _this._updateParameters();
  79302. });
  79303. }
  79304. // Ensure the effect will be rebuilt.
  79305. if (!doNotBuild) {
  79306. this._updateParameters();
  79307. }
  79308. };
  79309. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  79310. /**
  79311. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79312. */
  79313. get: function () {
  79314. return this.imageProcessingConfiguration.colorCurves;
  79315. },
  79316. /**
  79317. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79318. */
  79319. set: function (value) {
  79320. this.imageProcessingConfiguration.colorCurves = value;
  79321. },
  79322. enumerable: true,
  79323. configurable: true
  79324. });
  79325. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  79326. /**
  79327. * Gets wether the color curves effect is enabled.
  79328. */
  79329. get: function () {
  79330. return this.imageProcessingConfiguration.colorCurvesEnabled;
  79331. },
  79332. /**
  79333. * Sets wether the color curves effect is enabled.
  79334. */
  79335. set: function (value) {
  79336. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  79337. },
  79338. enumerable: true,
  79339. configurable: true
  79340. });
  79341. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  79342. /**
  79343. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79344. */
  79345. get: function () {
  79346. return this.imageProcessingConfiguration.colorGradingTexture;
  79347. },
  79348. /**
  79349. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79350. */
  79351. set: function (value) {
  79352. this.imageProcessingConfiguration.colorGradingTexture = value;
  79353. },
  79354. enumerable: true,
  79355. configurable: true
  79356. });
  79357. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  79358. /**
  79359. * Gets wether the color grading effect is enabled.
  79360. */
  79361. get: function () {
  79362. return this.imageProcessingConfiguration.colorGradingEnabled;
  79363. },
  79364. /**
  79365. * Gets wether the color grading effect is enabled.
  79366. */
  79367. set: function (value) {
  79368. this.imageProcessingConfiguration.colorGradingEnabled = value;
  79369. },
  79370. enumerable: true,
  79371. configurable: true
  79372. });
  79373. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  79374. /**
  79375. * Gets exposure used in the effect.
  79376. */
  79377. get: function () {
  79378. return this.imageProcessingConfiguration.exposure;
  79379. },
  79380. /**
  79381. * Sets exposure used in the effect.
  79382. */
  79383. set: function (value) {
  79384. this.imageProcessingConfiguration.exposure = value;
  79385. },
  79386. enumerable: true,
  79387. configurable: true
  79388. });
  79389. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  79390. /**
  79391. * Gets wether tonemapping is enabled or not.
  79392. */
  79393. get: function () {
  79394. return this._imageProcessingConfiguration.toneMappingEnabled;
  79395. },
  79396. /**
  79397. * Sets wether tonemapping is enabled or not
  79398. */
  79399. set: function (value) {
  79400. this._imageProcessingConfiguration.toneMappingEnabled = value;
  79401. },
  79402. enumerable: true,
  79403. configurable: true
  79404. });
  79405. ;
  79406. ;
  79407. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  79408. /**
  79409. * Gets contrast used in the effect.
  79410. */
  79411. get: function () {
  79412. return this.imageProcessingConfiguration.contrast;
  79413. },
  79414. /**
  79415. * Sets contrast used in the effect.
  79416. */
  79417. set: function (value) {
  79418. this.imageProcessingConfiguration.contrast = value;
  79419. },
  79420. enumerable: true,
  79421. configurable: true
  79422. });
  79423. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  79424. /**
  79425. * Gets Vignette stretch size.
  79426. */
  79427. get: function () {
  79428. return this.imageProcessingConfiguration.vignetteStretch;
  79429. },
  79430. /**
  79431. * Sets Vignette stretch size.
  79432. */
  79433. set: function (value) {
  79434. this.imageProcessingConfiguration.vignetteStretch = value;
  79435. },
  79436. enumerable: true,
  79437. configurable: true
  79438. });
  79439. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  79440. /**
  79441. * Gets Vignette centre X Offset.
  79442. */
  79443. get: function () {
  79444. return this.imageProcessingConfiguration.vignetteCentreX;
  79445. },
  79446. /**
  79447. * Sets Vignette centre X Offset.
  79448. */
  79449. set: function (value) {
  79450. this.imageProcessingConfiguration.vignetteCentreX = value;
  79451. },
  79452. enumerable: true,
  79453. configurable: true
  79454. });
  79455. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  79456. /**
  79457. * Gets Vignette centre Y Offset.
  79458. */
  79459. get: function () {
  79460. return this.imageProcessingConfiguration.vignetteCentreY;
  79461. },
  79462. /**
  79463. * Sets Vignette centre Y Offset.
  79464. */
  79465. set: function (value) {
  79466. this.imageProcessingConfiguration.vignetteCentreY = value;
  79467. },
  79468. enumerable: true,
  79469. configurable: true
  79470. });
  79471. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  79472. /**
  79473. * Gets Vignette weight or intensity of the vignette effect.
  79474. */
  79475. get: function () {
  79476. return this.imageProcessingConfiguration.vignetteWeight;
  79477. },
  79478. /**
  79479. * Sets Vignette weight or intensity of the vignette effect.
  79480. */
  79481. set: function (value) {
  79482. this.imageProcessingConfiguration.vignetteWeight = value;
  79483. },
  79484. enumerable: true,
  79485. configurable: true
  79486. });
  79487. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  79488. /**
  79489. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79490. * if vignetteEnabled is set to true.
  79491. */
  79492. get: function () {
  79493. return this.imageProcessingConfiguration.vignetteColor;
  79494. },
  79495. /**
  79496. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79497. * if vignetteEnabled is set to true.
  79498. */
  79499. set: function (value) {
  79500. this.imageProcessingConfiguration.vignetteColor = value;
  79501. },
  79502. enumerable: true,
  79503. configurable: true
  79504. });
  79505. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  79506. /**
  79507. * Gets Camera field of view used by the Vignette effect.
  79508. */
  79509. get: function () {
  79510. return this.imageProcessingConfiguration.vignetteCameraFov;
  79511. },
  79512. /**
  79513. * Sets Camera field of view used by the Vignette effect.
  79514. */
  79515. set: function (value) {
  79516. this.imageProcessingConfiguration.vignetteCameraFov = value;
  79517. },
  79518. enumerable: true,
  79519. configurable: true
  79520. });
  79521. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  79522. /**
  79523. * Gets the vignette blend mode allowing different kind of effect.
  79524. */
  79525. get: function () {
  79526. return this.imageProcessingConfiguration.vignetteBlendMode;
  79527. },
  79528. /**
  79529. * Sets the vignette blend mode allowing different kind of effect.
  79530. */
  79531. set: function (value) {
  79532. this.imageProcessingConfiguration.vignetteBlendMode = value;
  79533. },
  79534. enumerable: true,
  79535. configurable: true
  79536. });
  79537. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  79538. /**
  79539. * Gets wether the vignette effect is enabled.
  79540. */
  79541. get: function () {
  79542. return this.imageProcessingConfiguration.vignetteEnabled;
  79543. },
  79544. /**
  79545. * Sets wether the vignette effect is enabled.
  79546. */
  79547. set: function (value) {
  79548. this.imageProcessingConfiguration.vignetteEnabled = value;
  79549. },
  79550. enumerable: true,
  79551. configurable: true
  79552. });
  79553. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  79554. /**
  79555. * Gets wether the input of the processing is in Gamma or Linear Space.
  79556. */
  79557. get: function () {
  79558. return this._fromLinearSpace;
  79559. },
  79560. /**
  79561. * Sets wether the input of the processing is in Gamma or Linear Space.
  79562. */
  79563. set: function (value) {
  79564. if (this._fromLinearSpace === value) {
  79565. return;
  79566. }
  79567. this._fromLinearSpace = value;
  79568. this._updateParameters();
  79569. },
  79570. enumerable: true,
  79571. configurable: true
  79572. });
  79573. ImageProcessingPostProcess.prototype.getClassName = function () {
  79574. return "ImageProcessingPostProcess";
  79575. };
  79576. ImageProcessingPostProcess.prototype._updateParameters = function () {
  79577. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  79578. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  79579. var defines = "";
  79580. for (var define in this._defines) {
  79581. if (this._defines[define]) {
  79582. defines += "#define " + define + ";\r\n";
  79583. }
  79584. }
  79585. var samplers = ["textureSampler"];
  79586. var uniforms = ["scale"];
  79587. if (BABYLON.ImageProcessingConfiguration) {
  79588. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  79589. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  79590. }
  79591. this.updateEffect(defines, uniforms, samplers);
  79592. };
  79593. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  79594. _super.prototype.dispose.call(this, camera);
  79595. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79596. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79597. }
  79598. if (this._imageProcessingConfiguration) {
  79599. this.imageProcessingConfiguration.applyByPostProcess = false;
  79600. }
  79601. };
  79602. __decorate([
  79603. BABYLON.serialize()
  79604. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  79605. return ImageProcessingPostProcess;
  79606. }(BABYLON.PostProcess));
  79607. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  79608. })(BABYLON || (BABYLON = {}));
  79609. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  79610. var BABYLON;
  79611. (function (BABYLON) {
  79612. /**
  79613. * Class used to store bone information
  79614. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79615. */
  79616. var Bone = /** @class */ (function (_super) {
  79617. __extends(Bone, _super);
  79618. /**
  79619. * Create a new bone
  79620. * @param name defines the bone name
  79621. * @param skeleton defines the parent skeleton
  79622. * @param parentBone defines the parent (can be null if the bone is the root)
  79623. * @param localMatrix defines the local matrix
  79624. * @param restPose defines the rest pose matrix
  79625. * @param baseMatrix defines the base matrix
  79626. * @param index defines index of the bone in the hiearchy
  79627. */
  79628. function Bone(
  79629. /**
  79630. * defines the bone name
  79631. */
  79632. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  79633. if (parentBone === void 0) { parentBone = null; }
  79634. if (localMatrix === void 0) { localMatrix = null; }
  79635. if (restPose === void 0) { restPose = null; }
  79636. if (baseMatrix === void 0) { baseMatrix = null; }
  79637. if (index === void 0) { index = null; }
  79638. var _this = _super.call(this, name, skeleton.getScene()) || this;
  79639. _this.name = name;
  79640. /**
  79641. * Gets the list of child bones
  79642. */
  79643. _this.children = new Array();
  79644. /** Gets the animations associated with this bone */
  79645. _this.animations = new Array();
  79646. /**
  79647. * @hidden Internal only
  79648. * Set this value to map this bone to a different index in the transform matrices
  79649. * Set this value to -1 to exclude the bone from the transform matrices
  79650. */
  79651. _this._index = null;
  79652. _this._absoluteTransform = new BABYLON.Matrix();
  79653. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  79654. _this._scalingDeterminant = 1;
  79655. _this._worldTransform = new BABYLON.Matrix();
  79656. _this._needToDecompose = true;
  79657. _this._needToCompose = false;
  79658. _this._skeleton = skeleton;
  79659. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  79660. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  79661. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  79662. _this._index = index;
  79663. skeleton.bones.push(_this);
  79664. _this.setParent(parentBone, false);
  79665. if (baseMatrix || localMatrix) {
  79666. _this._updateDifferenceMatrix();
  79667. }
  79668. return _this;
  79669. }
  79670. Object.defineProperty(Bone.prototype, "_matrix", {
  79671. /** @hidden */
  79672. get: function () {
  79673. this._compose();
  79674. return this._localMatrix;
  79675. },
  79676. /** @hidden */
  79677. set: function (value) {
  79678. this._localMatrix.copyFrom(value);
  79679. this._needToDecompose = true;
  79680. },
  79681. enumerable: true,
  79682. configurable: true
  79683. });
  79684. // Members
  79685. /**
  79686. * Gets the parent skeleton
  79687. * @returns a skeleton
  79688. */
  79689. Bone.prototype.getSkeleton = function () {
  79690. return this._skeleton;
  79691. };
  79692. /**
  79693. * Gets parent bone
  79694. * @returns a bone or null if the bone is the root of the bone hierarchy
  79695. */
  79696. Bone.prototype.getParent = function () {
  79697. return this._parent;
  79698. };
  79699. /**
  79700. * Sets the parent bone
  79701. * @param parent defines the parent (can be null if the bone is the root)
  79702. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79703. */
  79704. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  79705. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79706. if (this._parent === parent) {
  79707. return;
  79708. }
  79709. if (this._parent) {
  79710. var index = this._parent.children.indexOf(this);
  79711. if (index !== -1) {
  79712. this._parent.children.splice(index, 1);
  79713. }
  79714. }
  79715. this._parent = parent;
  79716. if (this._parent) {
  79717. this._parent.children.push(this);
  79718. }
  79719. if (updateDifferenceMatrix) {
  79720. this._updateDifferenceMatrix();
  79721. }
  79722. this.markAsDirty();
  79723. };
  79724. /**
  79725. * Gets the local matrix
  79726. * @returns a matrix
  79727. */
  79728. Bone.prototype.getLocalMatrix = function () {
  79729. this._compose();
  79730. return this._localMatrix;
  79731. };
  79732. /**
  79733. * Gets the base matrix (initial matrix which remains unchanged)
  79734. * @returns a matrix
  79735. */
  79736. Bone.prototype.getBaseMatrix = function () {
  79737. return this._baseMatrix;
  79738. };
  79739. /**
  79740. * Gets the rest pose matrix
  79741. * @returns a matrix
  79742. */
  79743. Bone.prototype.getRestPose = function () {
  79744. return this._restPose;
  79745. };
  79746. /**
  79747. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  79748. */
  79749. Bone.prototype.getWorldMatrix = function () {
  79750. return this._worldTransform;
  79751. };
  79752. /**
  79753. * Sets the local matrix to rest pose matrix
  79754. */
  79755. Bone.prototype.returnToRest = function () {
  79756. this.updateMatrix(this._restPose.clone());
  79757. };
  79758. /**
  79759. * Gets the inverse of the absolute transform matrix.
  79760. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  79761. * @returns a matrix
  79762. */
  79763. Bone.prototype.getInvertedAbsoluteTransform = function () {
  79764. return this._invertedAbsoluteTransform;
  79765. };
  79766. /**
  79767. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  79768. * @returns a matrix
  79769. */
  79770. Bone.prototype.getAbsoluteTransform = function () {
  79771. return this._absoluteTransform;
  79772. };
  79773. Object.defineProperty(Bone.prototype, "position", {
  79774. // Properties (matches AbstractMesh properties)
  79775. /** Gets or sets current position (in local space) */
  79776. get: function () {
  79777. this._decompose();
  79778. return this._localPosition;
  79779. },
  79780. set: function (newPosition) {
  79781. this._decompose();
  79782. this._localPosition.copyFrom(newPosition);
  79783. this._markAsDirtyAndCompose();
  79784. },
  79785. enumerable: true,
  79786. configurable: true
  79787. });
  79788. Object.defineProperty(Bone.prototype, "rotation", {
  79789. /** Gets or sets current rotation (in local space) */
  79790. get: function () {
  79791. return this.getRotation();
  79792. },
  79793. set: function (newRotation) {
  79794. this.setRotation(newRotation);
  79795. },
  79796. enumerable: true,
  79797. configurable: true
  79798. });
  79799. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  79800. /** Gets or sets current rotation quaternion (in local space) */
  79801. get: function () {
  79802. this._decompose();
  79803. return this._localRotation;
  79804. },
  79805. set: function (newRotation) {
  79806. this.setRotationQuaternion(newRotation);
  79807. },
  79808. enumerable: true,
  79809. configurable: true
  79810. });
  79811. Object.defineProperty(Bone.prototype, "scaling", {
  79812. /** Gets or sets current scaling (in local space) */
  79813. get: function () {
  79814. return this.getScale();
  79815. },
  79816. set: function (newScaling) {
  79817. this.setScale(newScaling);
  79818. },
  79819. enumerable: true,
  79820. configurable: true
  79821. });
  79822. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  79823. /**
  79824. * Gets the animation properties override
  79825. */
  79826. get: function () {
  79827. return this._skeleton.animationPropertiesOverride;
  79828. },
  79829. enumerable: true,
  79830. configurable: true
  79831. });
  79832. // Methods
  79833. Bone.prototype._decompose = function () {
  79834. if (!this._needToDecompose) {
  79835. return;
  79836. }
  79837. this._needToDecompose = false;
  79838. if (!this._localScaling) {
  79839. this._localScaling = BABYLON.Vector3.Zero();
  79840. this._localRotation = BABYLON.Quaternion.Zero();
  79841. this._localPosition = BABYLON.Vector3.Zero();
  79842. }
  79843. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  79844. };
  79845. Bone.prototype._compose = function () {
  79846. if (!this._needToCompose) {
  79847. return;
  79848. }
  79849. this._needToCompose = false;
  79850. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  79851. };
  79852. /**
  79853. * Update the base and local matrices
  79854. * @param matrix defines the new base or local matrix
  79855. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79856. * @param updateLocalMatrix defines if the local matrix should be updated
  79857. */
  79858. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  79859. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79860. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  79861. this._baseMatrix.copyFrom(matrix);
  79862. if (updateDifferenceMatrix) {
  79863. this._updateDifferenceMatrix();
  79864. }
  79865. if (updateLocalMatrix) {
  79866. this._localMatrix.copyFrom(matrix);
  79867. this._markAsDirtyAndDecompose();
  79868. }
  79869. else {
  79870. this.markAsDirty();
  79871. }
  79872. };
  79873. /** @hidden */
  79874. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  79875. if (updateChildren === void 0) { updateChildren = true; }
  79876. if (!rootMatrix) {
  79877. rootMatrix = this._baseMatrix;
  79878. }
  79879. if (this._parent) {
  79880. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79881. }
  79882. else {
  79883. this._absoluteTransform.copyFrom(rootMatrix);
  79884. }
  79885. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  79886. if (updateChildren) {
  79887. for (var index = 0; index < this.children.length; index++) {
  79888. this.children[index]._updateDifferenceMatrix();
  79889. }
  79890. }
  79891. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  79892. };
  79893. /**
  79894. * Flag the bone as dirty (Forcing it to update everything)
  79895. */
  79896. Bone.prototype.markAsDirty = function () {
  79897. this._currentRenderId++;
  79898. this._childRenderId++;
  79899. this._skeleton._markAsDirty();
  79900. };
  79901. Bone.prototype._markAsDirtyAndCompose = function () {
  79902. this.markAsDirty();
  79903. this._needToCompose = true;
  79904. };
  79905. Bone.prototype._markAsDirtyAndDecompose = function () {
  79906. this.markAsDirty();
  79907. this._needToDecompose = true;
  79908. };
  79909. /**
  79910. * Copy an animation range from another bone
  79911. * @param source defines the source bone
  79912. * @param rangeName defines the range name to copy
  79913. * @param frameOffset defines the frame offset
  79914. * @param rescaleAsRequired defines if rescaling must be applied if required
  79915. * @param skelDimensionsRatio defines the scaling ratio
  79916. * @returns true if operation was successful
  79917. */
  79918. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  79919. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79920. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  79921. // all animation may be coming from a library skeleton, so may need to create animation
  79922. if (this.animations.length === 0) {
  79923. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  79924. this.animations[0].setKeys([]);
  79925. }
  79926. // get animation info / verify there is such a range from the source bone
  79927. var sourceRange = source.animations[0].getRange(rangeName);
  79928. if (!sourceRange) {
  79929. return false;
  79930. }
  79931. var from = sourceRange.from;
  79932. var to = sourceRange.to;
  79933. var sourceKeys = source.animations[0].getKeys();
  79934. // rescaling prep
  79935. var sourceBoneLength = source.length;
  79936. var sourceParent = source.getParent();
  79937. var parent = this.getParent();
  79938. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  79939. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  79940. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  79941. var destKeys = this.animations[0].getKeys();
  79942. // loop vars declaration
  79943. var orig;
  79944. var origTranslation;
  79945. var mat;
  79946. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  79947. orig = sourceKeys[key];
  79948. if (orig.frame >= from && orig.frame <= to) {
  79949. if (rescaleAsRequired) {
  79950. mat = orig.value.clone();
  79951. // scale based on parent ratio, when bone has parent
  79952. if (parentScalingReqd) {
  79953. origTranslation = mat.getTranslation();
  79954. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  79955. // scale based on skeleton dimension ratio when root bone, and value is passed
  79956. }
  79957. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  79958. origTranslation = mat.getTranslation();
  79959. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  79960. // use original when root bone, and no data for skelDimensionsRatio
  79961. }
  79962. else {
  79963. mat = orig.value;
  79964. }
  79965. }
  79966. else {
  79967. mat = orig.value;
  79968. }
  79969. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  79970. }
  79971. }
  79972. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  79973. return true;
  79974. };
  79975. /**
  79976. * Translate the bone in local or world space
  79977. * @param vec The amount to translate the bone
  79978. * @param space The space that the translation is in
  79979. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79980. */
  79981. Bone.prototype.translate = function (vec, space, mesh) {
  79982. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79983. var lm = this.getLocalMatrix();
  79984. if (space == BABYLON.Space.LOCAL) {
  79985. lm.m[12] += vec.x;
  79986. lm.m[13] += vec.y;
  79987. lm.m[14] += vec.z;
  79988. }
  79989. else {
  79990. var wm = null;
  79991. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79992. if (mesh) {
  79993. wm = mesh.getWorldMatrix();
  79994. }
  79995. this._skeleton.computeAbsoluteTransforms();
  79996. var tmat = Bone._tmpMats[0];
  79997. var tvec = Bone._tmpVecs[0];
  79998. if (this._parent) {
  79999. if (mesh && wm) {
  80000. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80001. tmat.multiplyToRef(wm, tmat);
  80002. }
  80003. else {
  80004. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80005. }
  80006. }
  80007. tmat.m[12] = 0;
  80008. tmat.m[13] = 0;
  80009. tmat.m[14] = 0;
  80010. tmat.invert();
  80011. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  80012. lm.m[12] += tvec.x;
  80013. lm.m[13] += tvec.y;
  80014. lm.m[14] += tvec.z;
  80015. }
  80016. this._markAsDirtyAndDecompose();
  80017. };
  80018. /**
  80019. * Set the postion of the bone in local or world space
  80020. * @param position The position to set the bone
  80021. * @param space The space that the position is in
  80022. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80023. */
  80024. Bone.prototype.setPosition = function (position, space, mesh) {
  80025. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80026. var lm = this.getLocalMatrix();
  80027. if (space == BABYLON.Space.LOCAL) {
  80028. lm.m[12] = position.x;
  80029. lm.m[13] = position.y;
  80030. lm.m[14] = position.z;
  80031. }
  80032. else {
  80033. var wm = null;
  80034. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80035. if (mesh) {
  80036. wm = mesh.getWorldMatrix();
  80037. }
  80038. this._skeleton.computeAbsoluteTransforms();
  80039. var tmat = Bone._tmpMats[0];
  80040. var vec = Bone._tmpVecs[0];
  80041. if (this._parent) {
  80042. if (mesh && wm) {
  80043. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80044. tmat.multiplyToRef(wm, tmat);
  80045. }
  80046. else {
  80047. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80048. }
  80049. }
  80050. tmat.invert();
  80051. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  80052. lm.m[12] = vec.x;
  80053. lm.m[13] = vec.y;
  80054. lm.m[14] = vec.z;
  80055. }
  80056. this._markAsDirtyAndDecompose();
  80057. };
  80058. /**
  80059. * Set the absolute position of the bone (world space)
  80060. * @param position The position to set the bone
  80061. * @param mesh The mesh that this bone is attached to
  80062. */
  80063. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  80064. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  80065. };
  80066. /**
  80067. * Scale the bone on the x, y and z axes (in local space)
  80068. * @param x The amount to scale the bone on the x axis
  80069. * @param y The amount to scale the bone on the y axis
  80070. * @param z The amount to scale the bone on the z axis
  80071. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  80072. */
  80073. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  80074. if (scaleChildren === void 0) { scaleChildren = false; }
  80075. var locMat = this.getLocalMatrix();
  80076. // Apply new scaling on top of current local matrix
  80077. var scaleMat = Bone._tmpMats[0];
  80078. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  80079. scaleMat.multiplyToRef(locMat, locMat);
  80080. // Invert scaling matrix and apply the inverse to all children
  80081. scaleMat.invert();
  80082. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  80083. var child = _a[_i];
  80084. var cm = child.getLocalMatrix();
  80085. cm.multiplyToRef(scaleMat, cm);
  80086. cm.m[12] *= x;
  80087. cm.m[13] *= y;
  80088. cm.m[14] *= z;
  80089. child._markAsDirtyAndDecompose();
  80090. }
  80091. this._markAsDirtyAndDecompose();
  80092. if (scaleChildren) {
  80093. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  80094. var child = _c[_b];
  80095. child.scale(x, y, z, scaleChildren);
  80096. }
  80097. }
  80098. };
  80099. /**
  80100. * Set the bone scaling in local space
  80101. * @param scale defines the scaling vector
  80102. */
  80103. Bone.prototype.setScale = function (scale) {
  80104. this._decompose();
  80105. this._localScaling.copyFrom(scale);
  80106. this._markAsDirtyAndCompose();
  80107. };
  80108. /**
  80109. * Gets the current scaling in local space
  80110. * @returns the current scaling vector
  80111. */
  80112. Bone.prototype.getScale = function () {
  80113. this._decompose();
  80114. return this._localScaling;
  80115. };
  80116. /**
  80117. * Gets the current scaling in local space and stores it in a target vector
  80118. * @param result defines the target vector
  80119. */
  80120. Bone.prototype.getScaleToRef = function (result) {
  80121. this._decompose();
  80122. result.copyFrom(this._localScaling);
  80123. };
  80124. /**
  80125. * Set the yaw, pitch, and roll of the bone in local or world space
  80126. * @param yaw The rotation of the bone on the y axis
  80127. * @param pitch The rotation of the bone on the x axis
  80128. * @param roll The rotation of the bone on the z axis
  80129. * @param space The space that the axes of rotation are in
  80130. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80131. */
  80132. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  80133. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80134. if (space === BABYLON.Space.LOCAL) {
  80135. var quat = Bone._tmpQuat;
  80136. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  80137. this.setRotationQuaternion(quat, space, mesh);
  80138. return;
  80139. }
  80140. var rotMatInv = Bone._tmpMats[0];
  80141. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80142. return;
  80143. }
  80144. var rotMat = Bone._tmpMats[1];
  80145. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  80146. rotMatInv.multiplyToRef(rotMat, rotMat);
  80147. this._rotateWithMatrix(rotMat, space, mesh);
  80148. };
  80149. /**
  80150. * Add a rotation to the bone on an axis in local or world space
  80151. * @param axis The axis to rotate the bone on
  80152. * @param amount The amount to rotate the bone
  80153. * @param space The space that the axis is in
  80154. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80155. */
  80156. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  80157. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80158. var rmat = Bone._tmpMats[0];
  80159. rmat.m[12] = 0;
  80160. rmat.m[13] = 0;
  80161. rmat.m[14] = 0;
  80162. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  80163. this._rotateWithMatrix(rmat, space, mesh);
  80164. };
  80165. /**
  80166. * Set the rotation of the bone to a particular axis angle in local or world space
  80167. * @param axis The axis to rotate the bone on
  80168. * @param angle The angle that the bone should be rotated to
  80169. * @param space The space that the axis is in
  80170. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80171. */
  80172. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  80173. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80174. if (space === BABYLON.Space.LOCAL) {
  80175. var quat = Bone._tmpQuat;
  80176. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  80177. this.setRotationQuaternion(quat, space, mesh);
  80178. return;
  80179. }
  80180. var rotMatInv = Bone._tmpMats[0];
  80181. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80182. return;
  80183. }
  80184. var rotMat = Bone._tmpMats[1];
  80185. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  80186. rotMatInv.multiplyToRef(rotMat, rotMat);
  80187. this._rotateWithMatrix(rotMat, space, mesh);
  80188. };
  80189. /**
  80190. * Set the euler rotation of the bone in local of world space
  80191. * @param rotation The euler rotation that the bone should be set to
  80192. * @param space The space that the rotation is in
  80193. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80194. */
  80195. Bone.prototype.setRotation = function (rotation, space, mesh) {
  80196. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80197. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  80198. };
  80199. /**
  80200. * Set the quaternion rotation of the bone in local of world space
  80201. * @param quat The quaternion rotation that the bone should be set to
  80202. * @param space The space that the rotation is in
  80203. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80204. */
  80205. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  80206. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80207. if (space === BABYLON.Space.LOCAL) {
  80208. this._decompose();
  80209. this._localRotation.copyFrom(quat);
  80210. this._markAsDirtyAndCompose();
  80211. return;
  80212. }
  80213. var rotMatInv = Bone._tmpMats[0];
  80214. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80215. return;
  80216. }
  80217. var rotMat = Bone._tmpMats[1];
  80218. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  80219. rotMatInv.multiplyToRef(rotMat, rotMat);
  80220. this._rotateWithMatrix(rotMat, space, mesh);
  80221. };
  80222. /**
  80223. * Set the rotation matrix of the bone in local of world space
  80224. * @param rotMat The rotation matrix that the bone should be set to
  80225. * @param space The space that the rotation is in
  80226. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80227. */
  80228. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  80229. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80230. if (space === BABYLON.Space.LOCAL) {
  80231. var quat = Bone._tmpQuat;
  80232. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  80233. this.setRotationQuaternion(quat, space, mesh);
  80234. return;
  80235. }
  80236. var rotMatInv = Bone._tmpMats[0];
  80237. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80238. return;
  80239. }
  80240. var rotMat2 = Bone._tmpMats[1];
  80241. rotMat2.copyFrom(rotMat);
  80242. rotMatInv.multiplyToRef(rotMat, rotMat2);
  80243. this._rotateWithMatrix(rotMat2, space, mesh);
  80244. };
  80245. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  80246. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80247. var lmat = this.getLocalMatrix();
  80248. var lx = lmat.m[12];
  80249. var ly = lmat.m[13];
  80250. var lz = lmat.m[14];
  80251. var parent = this.getParent();
  80252. var parentScale = Bone._tmpMats[3];
  80253. var parentScaleInv = Bone._tmpMats[4];
  80254. if (parent && space == BABYLON.Space.WORLD) {
  80255. if (mesh) {
  80256. parentScale.copyFrom(mesh.getWorldMatrix());
  80257. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  80258. }
  80259. else {
  80260. parentScale.copyFrom(parent.getAbsoluteTransform());
  80261. }
  80262. parentScaleInv.copyFrom(parentScale);
  80263. parentScaleInv.invert();
  80264. lmat.multiplyToRef(parentScale, lmat);
  80265. lmat.multiplyToRef(rmat, lmat);
  80266. lmat.multiplyToRef(parentScaleInv, lmat);
  80267. }
  80268. else {
  80269. if (space == BABYLON.Space.WORLD && mesh) {
  80270. parentScale.copyFrom(mesh.getWorldMatrix());
  80271. parentScaleInv.copyFrom(parentScale);
  80272. parentScaleInv.invert();
  80273. lmat.multiplyToRef(parentScale, lmat);
  80274. lmat.multiplyToRef(rmat, lmat);
  80275. lmat.multiplyToRef(parentScaleInv, lmat);
  80276. }
  80277. else {
  80278. lmat.multiplyToRef(rmat, lmat);
  80279. }
  80280. }
  80281. lmat.m[12] = lx;
  80282. lmat.m[13] = ly;
  80283. lmat.m[14] = lz;
  80284. this.computeAbsoluteTransforms();
  80285. this._markAsDirtyAndDecompose();
  80286. };
  80287. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  80288. var scaleMatrix = Bone._tmpMats[2];
  80289. rotMatInv.copyFrom(this.getAbsoluteTransform());
  80290. if (mesh) {
  80291. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  80292. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  80293. }
  80294. rotMatInv.invert();
  80295. if (isNaN(rotMatInv.m[0])) {
  80296. // Matrix failed to invert.
  80297. // This can happen if scale is zero for example.
  80298. return false;
  80299. }
  80300. scaleMatrix.m[0] *= this._scalingDeterminant;
  80301. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  80302. return true;
  80303. };
  80304. /**
  80305. * Get the position of the bone in local or world space
  80306. * @param space The space that the returned position is in
  80307. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80308. * @returns The position of the bone
  80309. */
  80310. Bone.prototype.getPosition = function (space, mesh) {
  80311. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80312. if (mesh === void 0) { mesh = null; }
  80313. var pos = BABYLON.Vector3.Zero();
  80314. this.getPositionToRef(space, mesh, pos);
  80315. return pos;
  80316. };
  80317. /**
  80318. * Copy the position of the bone to a vector3 in local or world space
  80319. * @param space The space that the returned position is in
  80320. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80321. * @param result The vector3 to copy the position to
  80322. */
  80323. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  80324. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80325. if (space == BABYLON.Space.LOCAL) {
  80326. var lm = this.getLocalMatrix();
  80327. result.x = lm.m[12];
  80328. result.y = lm.m[13];
  80329. result.z = lm.m[14];
  80330. }
  80331. else {
  80332. var wm = null;
  80333. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80334. if (mesh) {
  80335. wm = mesh.getWorldMatrix();
  80336. }
  80337. this._skeleton.computeAbsoluteTransforms();
  80338. var tmat = Bone._tmpMats[0];
  80339. if (mesh && wm) {
  80340. tmat.copyFrom(this.getAbsoluteTransform());
  80341. tmat.multiplyToRef(wm, tmat);
  80342. }
  80343. else {
  80344. tmat = this.getAbsoluteTransform();
  80345. }
  80346. result.x = tmat.m[12];
  80347. result.y = tmat.m[13];
  80348. result.z = tmat.m[14];
  80349. }
  80350. };
  80351. /**
  80352. * Get the absolute position of the bone (world space)
  80353. * @param mesh The mesh that this bone is attached to
  80354. * @returns The absolute position of the bone
  80355. */
  80356. Bone.prototype.getAbsolutePosition = function (mesh) {
  80357. if (mesh === void 0) { mesh = null; }
  80358. var pos = BABYLON.Vector3.Zero();
  80359. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  80360. return pos;
  80361. };
  80362. /**
  80363. * Copy the absolute position of the bone (world space) to the result param
  80364. * @param mesh The mesh that this bone is attached to
  80365. * @param result The vector3 to copy the absolute position to
  80366. */
  80367. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  80368. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  80369. };
  80370. /**
  80371. * Compute the absolute transforms of this bone and its children
  80372. */
  80373. Bone.prototype.computeAbsoluteTransforms = function () {
  80374. this._compose();
  80375. if (this._parent) {
  80376. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  80377. }
  80378. else {
  80379. this._absoluteTransform.copyFrom(this._localMatrix);
  80380. var poseMatrix = this._skeleton.getPoseMatrix();
  80381. if (poseMatrix) {
  80382. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  80383. }
  80384. }
  80385. var children = this.children;
  80386. var len = children.length;
  80387. for (var i = 0; i < len; i++) {
  80388. children[i].computeAbsoluteTransforms();
  80389. }
  80390. };
  80391. /**
  80392. * Get the world direction from an axis that is in the local space of the bone
  80393. * @param localAxis The local direction that is used to compute the world direction
  80394. * @param mesh The mesh that this bone is attached to
  80395. * @returns The world direction
  80396. */
  80397. Bone.prototype.getDirection = function (localAxis, mesh) {
  80398. if (mesh === void 0) { mesh = null; }
  80399. var result = BABYLON.Vector3.Zero();
  80400. this.getDirectionToRef(localAxis, mesh, result);
  80401. return result;
  80402. };
  80403. /**
  80404. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  80405. * @param localAxis The local direction that is used to compute the world direction
  80406. * @param mesh The mesh that this bone is attached to
  80407. * @param result The vector3 that the world direction will be copied to
  80408. */
  80409. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  80410. if (mesh === void 0) { mesh = null; }
  80411. var wm = null;
  80412. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80413. if (mesh) {
  80414. wm = mesh.getWorldMatrix();
  80415. }
  80416. this._skeleton.computeAbsoluteTransforms();
  80417. var mat = Bone._tmpMats[0];
  80418. mat.copyFrom(this.getAbsoluteTransform());
  80419. if (mesh && wm) {
  80420. mat.multiplyToRef(wm, mat);
  80421. }
  80422. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  80423. result.normalize();
  80424. };
  80425. /**
  80426. * Get the euler rotation of the bone in local or world space
  80427. * @param space The space that the rotation should be in
  80428. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80429. * @returns The euler rotation
  80430. */
  80431. Bone.prototype.getRotation = function (space, mesh) {
  80432. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80433. if (mesh === void 0) { mesh = null; }
  80434. var result = BABYLON.Vector3.Zero();
  80435. this.getRotationToRef(space, mesh, result);
  80436. return result;
  80437. };
  80438. /**
  80439. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  80440. * @param space The space that the rotation should be in
  80441. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80442. * @param result The vector3 that the rotation should be copied to
  80443. */
  80444. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  80445. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80446. if (mesh === void 0) { mesh = null; }
  80447. var quat = Bone._tmpQuat;
  80448. this.getRotationQuaternionToRef(space, mesh, quat);
  80449. quat.toEulerAnglesToRef(result);
  80450. };
  80451. /**
  80452. * Get the quaternion rotation of the bone in either local or world space
  80453. * @param space The space that the rotation should be in
  80454. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80455. * @returns The quaternion rotation
  80456. */
  80457. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  80458. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80459. if (mesh === void 0) { mesh = null; }
  80460. var result = BABYLON.Quaternion.Identity();
  80461. this.getRotationQuaternionToRef(space, mesh, result);
  80462. return result;
  80463. };
  80464. /**
  80465. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  80466. * @param space The space that the rotation should be in
  80467. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80468. * @param result The quaternion that the rotation should be copied to
  80469. */
  80470. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  80471. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80472. if (mesh === void 0) { mesh = null; }
  80473. if (space == BABYLON.Space.LOCAL) {
  80474. this._decompose();
  80475. result.copyFrom(this._localRotation);
  80476. }
  80477. else {
  80478. var mat = Bone._tmpMats[0];
  80479. var amat = this.getAbsoluteTransform();
  80480. if (mesh) {
  80481. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80482. }
  80483. else {
  80484. mat.copyFrom(amat);
  80485. }
  80486. mat.m[0] *= this._scalingDeterminant;
  80487. mat.m[1] *= this._scalingDeterminant;
  80488. mat.m[2] *= this._scalingDeterminant;
  80489. mat.decompose(undefined, result, undefined);
  80490. }
  80491. };
  80492. /**
  80493. * Get the rotation matrix of the bone in local or world space
  80494. * @param space The space that the rotation should be in
  80495. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80496. * @returns The rotation matrix
  80497. */
  80498. Bone.prototype.getRotationMatrix = function (space, mesh) {
  80499. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80500. var result = BABYLON.Matrix.Identity();
  80501. this.getRotationMatrixToRef(space, mesh, result);
  80502. return result;
  80503. };
  80504. /**
  80505. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  80506. * @param space The space that the rotation should be in
  80507. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80508. * @param result The quaternion that the rotation should be copied to
  80509. */
  80510. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  80511. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80512. if (space == BABYLON.Space.LOCAL) {
  80513. this.getLocalMatrix().getRotationMatrixToRef(result);
  80514. }
  80515. else {
  80516. var mat = Bone._tmpMats[0];
  80517. var amat = this.getAbsoluteTransform();
  80518. if (mesh) {
  80519. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80520. }
  80521. else {
  80522. mat.copyFrom(amat);
  80523. }
  80524. mat.m[0] *= this._scalingDeterminant;
  80525. mat.m[1] *= this._scalingDeterminant;
  80526. mat.m[2] *= this._scalingDeterminant;
  80527. mat.getRotationMatrixToRef(result);
  80528. }
  80529. };
  80530. /**
  80531. * Get the world position of a point that is in the local space of the bone
  80532. * @param position The local position
  80533. * @param mesh The mesh that this bone is attached to
  80534. * @returns The world position
  80535. */
  80536. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  80537. if (mesh === void 0) { mesh = null; }
  80538. var result = BABYLON.Vector3.Zero();
  80539. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  80540. return result;
  80541. };
  80542. /**
  80543. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  80544. * @param position The local position
  80545. * @param mesh The mesh that this bone is attached to
  80546. * @param result The vector3 that the world position should be copied to
  80547. */
  80548. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  80549. if (mesh === void 0) { mesh = null; }
  80550. var wm = null;
  80551. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80552. if (mesh) {
  80553. wm = mesh.getWorldMatrix();
  80554. }
  80555. this._skeleton.computeAbsoluteTransforms();
  80556. var tmat = Bone._tmpMats[0];
  80557. if (mesh && wm) {
  80558. tmat.copyFrom(this.getAbsoluteTransform());
  80559. tmat.multiplyToRef(wm, tmat);
  80560. }
  80561. else {
  80562. tmat = this.getAbsoluteTransform();
  80563. }
  80564. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80565. };
  80566. /**
  80567. * Get the local position of a point that is in world space
  80568. * @param position The world position
  80569. * @param mesh The mesh that this bone is attached to
  80570. * @returns The local position
  80571. */
  80572. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  80573. if (mesh === void 0) { mesh = null; }
  80574. var result = BABYLON.Vector3.Zero();
  80575. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  80576. return result;
  80577. };
  80578. /**
  80579. * Get the local position of a point that is in world space and copy it to the result param
  80580. * @param position The world position
  80581. * @param mesh The mesh that this bone is attached to
  80582. * @param result The vector3 that the local position should be copied to
  80583. */
  80584. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  80585. if (mesh === void 0) { mesh = null; }
  80586. var wm = null;
  80587. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80588. if (mesh) {
  80589. wm = mesh.getWorldMatrix();
  80590. }
  80591. this._skeleton.computeAbsoluteTransforms();
  80592. var tmat = Bone._tmpMats[0];
  80593. tmat.copyFrom(this.getAbsoluteTransform());
  80594. if (mesh && wm) {
  80595. tmat.multiplyToRef(wm, tmat);
  80596. }
  80597. tmat.invert();
  80598. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80599. };
  80600. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80601. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  80602. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80603. return Bone;
  80604. }(BABYLON.Node));
  80605. BABYLON.Bone = Bone;
  80606. })(BABYLON || (BABYLON = {}));
  80607. //# sourceMappingURL=babylon.bone.js.map
  80608. var BABYLON;
  80609. (function (BABYLON) {
  80610. /**
  80611. * Class used to apply inverse kinematics to bones
  80612. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  80613. */
  80614. var BoneIKController = /** @class */ (function () {
  80615. /**
  80616. * Creates a new BoneIKController
  80617. * @param mesh defines the mesh to control
  80618. * @param bone defines the bone to control
  80619. * @param options defines options to set up the controller
  80620. */
  80621. function BoneIKController(mesh, bone, options) {
  80622. /**
  80623. * Gets or sets the target position
  80624. */
  80625. this.targetPosition = BABYLON.Vector3.Zero();
  80626. /**
  80627. * Gets or sets the pole target position
  80628. */
  80629. this.poleTargetPosition = BABYLON.Vector3.Zero();
  80630. /**
  80631. * Gets or sets the pole target local offset
  80632. */
  80633. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  80634. /**
  80635. * Gets or sets the pole angle
  80636. */
  80637. this.poleAngle = 0;
  80638. /**
  80639. * 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)
  80640. */
  80641. this.slerpAmount = 1;
  80642. this._bone1Quat = BABYLON.Quaternion.Identity();
  80643. this._bone1Mat = BABYLON.Matrix.Identity();
  80644. this._bone2Ang = Math.PI;
  80645. this._maxAngle = Math.PI;
  80646. this._rightHandedSystem = false;
  80647. this._bendAxis = BABYLON.Vector3.Right();
  80648. this._slerping = false;
  80649. this._adjustRoll = 0;
  80650. this._bone2 = bone;
  80651. this._bone1 = bone.getParent();
  80652. if (!this._bone1) {
  80653. return;
  80654. }
  80655. this.mesh = mesh;
  80656. var bonePos = bone.getPosition();
  80657. if (bone.getAbsoluteTransform().determinant() > 0) {
  80658. this._rightHandedSystem = true;
  80659. this._bendAxis.x = 0;
  80660. this._bendAxis.y = 0;
  80661. this._bendAxis.z = -1;
  80662. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  80663. this._adjustRoll = Math.PI * .5;
  80664. this._bendAxis.z = 1;
  80665. }
  80666. }
  80667. if (this._bone1.length) {
  80668. var boneScale1 = this._bone1.getScale();
  80669. var boneScale2 = this._bone2.getScale();
  80670. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  80671. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  80672. }
  80673. else if (this._bone1.children[0]) {
  80674. mesh.computeWorldMatrix(true);
  80675. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  80676. var pos2 = this._bone2.getAbsolutePosition(mesh);
  80677. var pos3 = this._bone1.getAbsolutePosition(mesh);
  80678. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  80679. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  80680. }
  80681. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  80682. this.maxAngle = Math.PI;
  80683. if (options) {
  80684. if (options.targetMesh) {
  80685. this.targetMesh = options.targetMesh;
  80686. this.targetMesh.computeWorldMatrix(true);
  80687. }
  80688. if (options.poleTargetMesh) {
  80689. this.poleTargetMesh = options.poleTargetMesh;
  80690. this.poleTargetMesh.computeWorldMatrix(true);
  80691. }
  80692. else if (options.poleTargetBone) {
  80693. this.poleTargetBone = options.poleTargetBone;
  80694. }
  80695. else if (this._bone1.getParent()) {
  80696. this.poleTargetBone = this._bone1.getParent();
  80697. }
  80698. if (options.poleTargetLocalOffset) {
  80699. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  80700. }
  80701. if (options.poleAngle) {
  80702. this.poleAngle = options.poleAngle;
  80703. }
  80704. if (options.bendAxis) {
  80705. this._bendAxis.copyFrom(options.bendAxis);
  80706. }
  80707. if (options.maxAngle) {
  80708. this.maxAngle = options.maxAngle;
  80709. }
  80710. if (options.slerpAmount) {
  80711. this.slerpAmount = options.slerpAmount;
  80712. }
  80713. }
  80714. }
  80715. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  80716. /**
  80717. * Gets or sets maximum allowed angle
  80718. */
  80719. get: function () {
  80720. return this._maxAngle;
  80721. },
  80722. set: function (value) {
  80723. this._setMaxAngle(value);
  80724. },
  80725. enumerable: true,
  80726. configurable: true
  80727. });
  80728. BoneIKController.prototype._setMaxAngle = function (ang) {
  80729. if (ang < 0) {
  80730. ang = 0;
  80731. }
  80732. if (ang > Math.PI || ang == undefined) {
  80733. ang = Math.PI;
  80734. }
  80735. this._maxAngle = ang;
  80736. var a = this._bone1Length;
  80737. var b = this._bone2Length;
  80738. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  80739. };
  80740. /**
  80741. * Force the controller to update the bones
  80742. */
  80743. BoneIKController.prototype.update = function () {
  80744. var bone1 = this._bone1;
  80745. if (!bone1) {
  80746. return;
  80747. }
  80748. var target = this.targetPosition;
  80749. var poleTarget = this.poleTargetPosition;
  80750. var mat1 = BoneIKController._tmpMats[0];
  80751. var mat2 = BoneIKController._tmpMats[1];
  80752. if (this.targetMesh) {
  80753. target.copyFrom(this.targetMesh.getAbsolutePosition());
  80754. }
  80755. if (this.poleTargetBone) {
  80756. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  80757. }
  80758. else if (this.poleTargetMesh) {
  80759. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  80760. }
  80761. var bonePos = BoneIKController._tmpVecs[0];
  80762. var zaxis = BoneIKController._tmpVecs[1];
  80763. var xaxis = BoneIKController._tmpVecs[2];
  80764. var yaxis = BoneIKController._tmpVecs[3];
  80765. var upAxis = BoneIKController._tmpVecs[4];
  80766. var _tmpQuat = BoneIKController._tmpQuat;
  80767. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  80768. poleTarget.subtractToRef(bonePos, upAxis);
  80769. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  80770. upAxis.y = 1;
  80771. }
  80772. else {
  80773. upAxis.normalize();
  80774. }
  80775. target.subtractToRef(bonePos, yaxis);
  80776. yaxis.normalize();
  80777. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  80778. zaxis.normalize();
  80779. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  80780. xaxis.normalize();
  80781. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  80782. var a = this._bone1Length;
  80783. var b = this._bone2Length;
  80784. var c = BABYLON.Vector3.Distance(bonePos, target);
  80785. if (this._maxReach > 0) {
  80786. c = Math.min(this._maxReach, c);
  80787. }
  80788. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  80789. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  80790. if (acosa > 1) {
  80791. acosa = 1;
  80792. }
  80793. if (acosb > 1) {
  80794. acosb = 1;
  80795. }
  80796. if (acosa < -1) {
  80797. acosa = -1;
  80798. }
  80799. if (acosb < -1) {
  80800. acosb = -1;
  80801. }
  80802. var angA = Math.acos(acosa);
  80803. var angB = Math.acos(acosb);
  80804. var angC = -angA - angB;
  80805. if (this._rightHandedSystem) {
  80806. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  80807. mat2.multiplyToRef(mat1, mat1);
  80808. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  80809. mat2.multiplyToRef(mat1, mat1);
  80810. }
  80811. else {
  80812. var _tmpVec = BoneIKController._tmpVecs[5];
  80813. _tmpVec.copyFrom(this._bendAxis);
  80814. _tmpVec.x *= -1;
  80815. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  80816. mat2.multiplyToRef(mat1, mat1);
  80817. }
  80818. if (this.poleAngle) {
  80819. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  80820. mat1.multiplyToRef(mat2, mat1);
  80821. }
  80822. if (this._bone1) {
  80823. if (this.slerpAmount < 1) {
  80824. if (!this._slerping) {
  80825. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  80826. }
  80827. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  80828. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  80829. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  80830. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  80831. this._slerping = true;
  80832. }
  80833. else {
  80834. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  80835. this._bone1Mat.copyFrom(mat1);
  80836. this._slerping = false;
  80837. }
  80838. }
  80839. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  80840. this._bone2Ang = angC;
  80841. };
  80842. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80843. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  80844. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80845. return BoneIKController;
  80846. }());
  80847. BABYLON.BoneIKController = BoneIKController;
  80848. })(BABYLON || (BABYLON = {}));
  80849. //# sourceMappingURL=babylon.boneIKController.js.map
  80850. var BABYLON;
  80851. (function (BABYLON) {
  80852. /**
  80853. * Class used to make a bone look toward a point in space
  80854. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  80855. */
  80856. var BoneLookController = /** @class */ (function () {
  80857. /**
  80858. * Create a BoneLookController
  80859. * @param mesh the mesh that the bone belongs to
  80860. * @param bone the bone that will be looking to the target
  80861. * @param target the target Vector3 to look at
  80862. * @param settings optional settings:
  80863. * * maxYaw: the maximum angle the bone will yaw to
  80864. * * minYaw: the minimum angle the bone will yaw to
  80865. * * maxPitch: the maximum angle the bone will pitch to
  80866. * * minPitch: the minimum angle the bone will yaw to
  80867. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  80868. * * upAxis: the up axis of the coordinate system
  80869. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  80870. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  80871. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  80872. * * adjustYaw: used to make an adjustment to the yaw of the bone
  80873. * * adjustPitch: used to make an adjustment to the pitch of the bone
  80874. * * adjustRoll: used to make an adjustment to the roll of the bone
  80875. **/
  80876. function BoneLookController(mesh, bone, target, options) {
  80877. /**
  80878. * The up axis of the coordinate system that is used when the bone is rotated
  80879. */
  80880. this.upAxis = BABYLON.Vector3.Up();
  80881. /**
  80882. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  80883. */
  80884. this.upAxisSpace = BABYLON.Space.LOCAL;
  80885. /**
  80886. * Used to make an adjustment to the yaw of the bone
  80887. */
  80888. this.adjustYaw = 0;
  80889. /**
  80890. * Used to make an adjustment to the pitch of the bone
  80891. */
  80892. this.adjustPitch = 0;
  80893. /**
  80894. * Used to make an adjustment to the roll of the bone
  80895. */
  80896. this.adjustRoll = 0;
  80897. /**
  80898. * 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)
  80899. */
  80900. this.slerpAmount = 1;
  80901. this._boneQuat = BABYLON.Quaternion.Identity();
  80902. this._slerping = false;
  80903. this._firstFrameSkipped = false;
  80904. this._fowardAxis = BABYLON.Vector3.Forward();
  80905. this.mesh = mesh;
  80906. this.bone = bone;
  80907. this.target = target;
  80908. if (options) {
  80909. if (options.adjustYaw) {
  80910. this.adjustYaw = options.adjustYaw;
  80911. }
  80912. if (options.adjustPitch) {
  80913. this.adjustPitch = options.adjustPitch;
  80914. }
  80915. if (options.adjustRoll) {
  80916. this.adjustRoll = options.adjustRoll;
  80917. }
  80918. if (options.maxYaw != null) {
  80919. this.maxYaw = options.maxYaw;
  80920. }
  80921. else {
  80922. this.maxYaw = Math.PI;
  80923. }
  80924. if (options.minYaw != null) {
  80925. this.minYaw = options.minYaw;
  80926. }
  80927. else {
  80928. this.minYaw = -Math.PI;
  80929. }
  80930. if (options.maxPitch != null) {
  80931. this.maxPitch = options.maxPitch;
  80932. }
  80933. else {
  80934. this.maxPitch = Math.PI;
  80935. }
  80936. if (options.minPitch != null) {
  80937. this.minPitch = options.minPitch;
  80938. }
  80939. else {
  80940. this.minPitch = -Math.PI;
  80941. }
  80942. if (options.slerpAmount != null) {
  80943. this.slerpAmount = options.slerpAmount;
  80944. }
  80945. if (options.upAxis != null) {
  80946. this.upAxis = options.upAxis;
  80947. }
  80948. if (options.upAxisSpace != null) {
  80949. this.upAxisSpace = options.upAxisSpace;
  80950. }
  80951. if (options.yawAxis != null || options.pitchAxis != null) {
  80952. var newYawAxis = BABYLON.Axis.Y;
  80953. var newPitchAxis = BABYLON.Axis.X;
  80954. if (options.yawAxis != null) {
  80955. newYawAxis = options.yawAxis.clone();
  80956. newYawAxis.normalize();
  80957. }
  80958. if (options.pitchAxis != null) {
  80959. newPitchAxis = options.pitchAxis.clone();
  80960. newPitchAxis.normalize();
  80961. }
  80962. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  80963. this._transformYawPitch = BABYLON.Matrix.Identity();
  80964. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  80965. this._transformYawPitchInv = this._transformYawPitch.clone();
  80966. this._transformYawPitch.invert();
  80967. }
  80968. }
  80969. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  80970. this.upAxisSpace = BABYLON.Space.LOCAL;
  80971. }
  80972. }
  80973. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  80974. /**
  80975. * Gets or sets the minimum yaw angle that the bone can look to
  80976. */
  80977. get: function () {
  80978. return this._minYaw;
  80979. },
  80980. set: function (value) {
  80981. this._minYaw = value;
  80982. this._minYawSin = Math.sin(value);
  80983. this._minYawCos = Math.cos(value);
  80984. if (this._maxYaw != null) {
  80985. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80986. this._yawRange = this._maxYaw - this._minYaw;
  80987. }
  80988. },
  80989. enumerable: true,
  80990. configurable: true
  80991. });
  80992. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  80993. /**
  80994. * Gets or sets the maximum yaw angle that the bone can look to
  80995. */
  80996. get: function () {
  80997. return this._maxYaw;
  80998. },
  80999. set: function (value) {
  81000. this._maxYaw = value;
  81001. this._maxYawSin = Math.sin(value);
  81002. this._maxYawCos = Math.cos(value);
  81003. if (this._minYaw != null) {
  81004. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  81005. this._yawRange = this._maxYaw - this._minYaw;
  81006. }
  81007. },
  81008. enumerable: true,
  81009. configurable: true
  81010. });
  81011. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  81012. /**
  81013. * Gets or sets the minimum pitch angle that the bone can look to
  81014. */
  81015. get: function () {
  81016. return this._minPitch;
  81017. },
  81018. set: function (value) {
  81019. this._minPitch = value;
  81020. this._minPitchTan = Math.tan(value);
  81021. },
  81022. enumerable: true,
  81023. configurable: true
  81024. });
  81025. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  81026. /**
  81027. * Gets or sets the maximum pitch angle that the bone can look to
  81028. */
  81029. get: function () {
  81030. return this._maxPitch;
  81031. },
  81032. set: function (value) {
  81033. this._maxPitch = value;
  81034. this._maxPitchTan = Math.tan(value);
  81035. },
  81036. enumerable: true,
  81037. configurable: true
  81038. });
  81039. /**
  81040. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  81041. */
  81042. BoneLookController.prototype.update = function () {
  81043. //skip the first frame when slerping so that the mesh rotation is correct
  81044. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  81045. this._firstFrameSkipped = true;
  81046. return;
  81047. }
  81048. var bone = this.bone;
  81049. var bonePos = BoneLookController._tmpVecs[0];
  81050. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  81051. var target = this.target;
  81052. var _tmpMat1 = BoneLookController._tmpMats[0];
  81053. var _tmpMat2 = BoneLookController._tmpMats[1];
  81054. var mesh = this.mesh;
  81055. var parentBone = bone.getParent();
  81056. var upAxis = BoneLookController._tmpVecs[1];
  81057. upAxis.copyFrom(this.upAxis);
  81058. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  81059. if (this._transformYawPitch) {
  81060. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  81061. }
  81062. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  81063. }
  81064. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  81065. mesh.getDirectionToRef(upAxis, upAxis);
  81066. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  81067. upAxis.normalize();
  81068. }
  81069. }
  81070. var checkYaw = false;
  81071. var checkPitch = false;
  81072. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  81073. checkYaw = true;
  81074. }
  81075. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  81076. checkPitch = true;
  81077. }
  81078. if (checkYaw || checkPitch) {
  81079. var spaceMat = BoneLookController._tmpMats[2];
  81080. var spaceMatInv = BoneLookController._tmpMats[3];
  81081. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  81082. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  81083. }
  81084. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  81085. spaceMat.copyFrom(mesh.getWorldMatrix());
  81086. }
  81087. else {
  81088. var forwardAxis = BoneLookController._tmpVecs[2];
  81089. forwardAxis.copyFrom(this._fowardAxis);
  81090. if (this._transformYawPitch) {
  81091. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  81092. }
  81093. if (parentBone) {
  81094. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  81095. }
  81096. else {
  81097. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  81098. }
  81099. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  81100. rightAxis.normalize();
  81101. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  81102. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  81103. }
  81104. spaceMat.invertToRef(spaceMatInv);
  81105. var xzlen = null;
  81106. if (checkPitch) {
  81107. var localTarget = BoneLookController._tmpVecs[3];
  81108. target.subtractToRef(bonePos, localTarget);
  81109. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  81110. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81111. var pitch = Math.atan2(localTarget.y, xzlen);
  81112. var newPitch = pitch;
  81113. if (pitch > this._maxPitch) {
  81114. localTarget.y = this._maxPitchTan * xzlen;
  81115. newPitch = this._maxPitch;
  81116. }
  81117. else if (pitch < this._minPitch) {
  81118. localTarget.y = this._minPitchTan * xzlen;
  81119. newPitch = this._minPitch;
  81120. }
  81121. if (pitch != newPitch) {
  81122. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81123. localTarget.addInPlace(bonePos);
  81124. target = localTarget;
  81125. }
  81126. }
  81127. if (checkYaw) {
  81128. var localTarget = BoneLookController._tmpVecs[4];
  81129. target.subtractToRef(bonePos, localTarget);
  81130. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  81131. var yaw = Math.atan2(localTarget.x, localTarget.z);
  81132. var newYaw = yaw;
  81133. if (yaw > this._maxYaw || yaw < this._minYaw) {
  81134. if (xzlen == null) {
  81135. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81136. }
  81137. if (this._yawRange > Math.PI) {
  81138. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  81139. localTarget.z = this._maxYawCos * xzlen;
  81140. localTarget.x = this._maxYawSin * xzlen;
  81141. newYaw = this._maxYaw;
  81142. }
  81143. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  81144. localTarget.z = this._minYawCos * xzlen;
  81145. localTarget.x = this._minYawSin * xzlen;
  81146. newYaw = this._minYaw;
  81147. }
  81148. }
  81149. else {
  81150. if (yaw > this._maxYaw) {
  81151. localTarget.z = this._maxYawCos * xzlen;
  81152. localTarget.x = this._maxYawSin * xzlen;
  81153. newYaw = this._maxYaw;
  81154. }
  81155. else if (yaw < this._minYaw) {
  81156. localTarget.z = this._minYawCos * xzlen;
  81157. localTarget.x = this._minYawSin * xzlen;
  81158. newYaw = this._minYaw;
  81159. }
  81160. }
  81161. }
  81162. if (this._slerping && this._yawRange > Math.PI) {
  81163. //are we going to be crossing into the min/max region?
  81164. var boneFwd = BoneLookController._tmpVecs[8];
  81165. boneFwd.copyFrom(BABYLON.Axis.Z);
  81166. if (this._transformYawPitch) {
  81167. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  81168. }
  81169. var boneRotMat = BoneLookController._tmpMats[4];
  81170. this._boneQuat.toRotationMatrix(boneRotMat);
  81171. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  81172. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  81173. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  81174. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  81175. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  81176. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  81177. if (angBtwTar > angBtwMidYaw) {
  81178. if (xzlen == null) {
  81179. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81180. }
  81181. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  81182. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  81183. if (angBtwMin < angBtwMax) {
  81184. newYaw = boneYaw + Math.PI * .75;
  81185. localTarget.z = Math.cos(newYaw) * xzlen;
  81186. localTarget.x = Math.sin(newYaw) * xzlen;
  81187. }
  81188. else {
  81189. newYaw = boneYaw - Math.PI * .75;
  81190. localTarget.z = Math.cos(newYaw) * xzlen;
  81191. localTarget.x = Math.sin(newYaw) * xzlen;
  81192. }
  81193. }
  81194. }
  81195. if (yaw != newYaw) {
  81196. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81197. localTarget.addInPlace(bonePos);
  81198. target = localTarget;
  81199. }
  81200. }
  81201. }
  81202. var zaxis = BoneLookController._tmpVecs[5];
  81203. var xaxis = BoneLookController._tmpVecs[6];
  81204. var yaxis = BoneLookController._tmpVecs[7];
  81205. var _tmpQuat = BoneLookController._tmpQuat;
  81206. target.subtractToRef(bonePos, zaxis);
  81207. zaxis.normalize();
  81208. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  81209. xaxis.normalize();
  81210. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  81211. yaxis.normalize();
  81212. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  81213. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  81214. return;
  81215. }
  81216. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  81217. return;
  81218. }
  81219. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  81220. return;
  81221. }
  81222. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  81223. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  81224. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  81225. }
  81226. if (this.slerpAmount < 1) {
  81227. if (!this._slerping) {
  81228. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  81229. }
  81230. if (this._transformYawPitch) {
  81231. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81232. }
  81233. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  81234. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  81235. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  81236. this._slerping = true;
  81237. }
  81238. else {
  81239. if (this._transformYawPitch) {
  81240. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81241. }
  81242. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  81243. this._slerping = false;
  81244. }
  81245. };
  81246. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  81247. var angDiff = ang2 - ang1;
  81248. angDiff %= Math.PI * 2;
  81249. if (angDiff > Math.PI) {
  81250. angDiff -= Math.PI * 2;
  81251. }
  81252. else if (angDiff < -Math.PI) {
  81253. angDiff += Math.PI * 2;
  81254. }
  81255. return angDiff;
  81256. };
  81257. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  81258. ang1 %= (2 * Math.PI);
  81259. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81260. ang2 %= (2 * Math.PI);
  81261. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81262. var ab = 0;
  81263. if (ang1 < ang2) {
  81264. ab = ang2 - ang1;
  81265. }
  81266. else {
  81267. ab = ang1 - ang2;
  81268. }
  81269. if (ab > Math.PI) {
  81270. ab = Math.PI * 2 - ab;
  81271. }
  81272. return ab;
  81273. };
  81274. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  81275. ang %= (2 * Math.PI);
  81276. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  81277. ang1 %= (2 * Math.PI);
  81278. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81279. ang2 %= (2 * Math.PI);
  81280. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81281. if (ang1 < ang2) {
  81282. if (ang > ang1 && ang < ang2) {
  81283. return true;
  81284. }
  81285. }
  81286. else {
  81287. if (ang > ang2 && ang < ang1) {
  81288. return true;
  81289. }
  81290. }
  81291. return false;
  81292. };
  81293. 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()];
  81294. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  81295. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81296. return BoneLookController;
  81297. }());
  81298. BABYLON.BoneLookController = BoneLookController;
  81299. })(BABYLON || (BABYLON = {}));
  81300. //# sourceMappingURL=babylon.boneLookController.js.map
  81301. var BABYLON;
  81302. (function (BABYLON) {
  81303. /**
  81304. * Class used to handle skinning animations
  81305. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  81306. */
  81307. var Skeleton = /** @class */ (function () {
  81308. /**
  81309. * Creates a new skeleton
  81310. * @param name defines the skeleton name
  81311. * @param id defines the skeleton Id
  81312. * @param scene defines the hosting scene
  81313. */
  81314. function Skeleton(
  81315. /** defines the skeleton name */
  81316. name,
  81317. /** defines the skeleton Id */
  81318. id, scene) {
  81319. this.name = name;
  81320. this.id = id;
  81321. /**
  81322. * Gets the list of child bones
  81323. */
  81324. this.bones = new Array();
  81325. /**
  81326. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  81327. */
  81328. this.needInitialSkinMatrix = false;
  81329. this._isDirty = true;
  81330. this._meshesWithPoseMatrix = new Array();
  81331. this._identity = BABYLON.Matrix.Identity();
  81332. this._ranges = {};
  81333. this._lastAbsoluteTransformsUpdateId = -1;
  81334. /**
  81335. * Specifies if the skeleton should be serialized
  81336. */
  81337. this.doNotSerialize = false;
  81338. this._animationPropertiesOverride = null;
  81339. // Events
  81340. /**
  81341. * An observable triggered before computing the skeleton's matrices
  81342. */
  81343. this.onBeforeComputeObservable = new BABYLON.Observable();
  81344. this.bones = [];
  81345. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81346. scene.skeletons.push(this);
  81347. //make sure it will recalculate the matrix next time prepare is called.
  81348. this._isDirty = true;
  81349. }
  81350. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  81351. /**
  81352. * Gets or sets the animation properties override
  81353. */
  81354. get: function () {
  81355. if (!this._animationPropertiesOverride) {
  81356. return this._scene.animationPropertiesOverride;
  81357. }
  81358. return this._animationPropertiesOverride;
  81359. },
  81360. set: function (value) {
  81361. this._animationPropertiesOverride = value;
  81362. },
  81363. enumerable: true,
  81364. configurable: true
  81365. });
  81366. // Members
  81367. /**
  81368. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  81369. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  81370. * @returns a Float32Array containing matrices data
  81371. */
  81372. Skeleton.prototype.getTransformMatrices = function (mesh) {
  81373. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  81374. return mesh._bonesTransformMatrices;
  81375. }
  81376. if (!this._transformMatrices) {
  81377. this.prepare();
  81378. }
  81379. return this._transformMatrices;
  81380. };
  81381. /**
  81382. * Gets the current hosting scene
  81383. * @returns a scene object
  81384. */
  81385. Skeleton.prototype.getScene = function () {
  81386. return this._scene;
  81387. };
  81388. // Methods
  81389. /**
  81390. * Gets a string representing the current skeleton data
  81391. * @param fullDetails defines a boolean indicating if we want a verbose version
  81392. * @returns a string representing the current skeleton data
  81393. */
  81394. Skeleton.prototype.toString = function (fullDetails) {
  81395. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  81396. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  81397. if (fullDetails) {
  81398. ret += ", Ranges: {";
  81399. var first = true;
  81400. for (var name_1 in this._ranges) {
  81401. if (first) {
  81402. ret += ", ";
  81403. first = false;
  81404. }
  81405. ret += name_1;
  81406. }
  81407. ret += "}";
  81408. }
  81409. return ret;
  81410. };
  81411. /**
  81412. * Get bone's index searching by name
  81413. * @param name defines bone's name to search for
  81414. * @return the indice of the bone. Returns -1 if not found
  81415. */
  81416. Skeleton.prototype.getBoneIndexByName = function (name) {
  81417. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  81418. if (this.bones[boneIndex].name === name) {
  81419. return boneIndex;
  81420. }
  81421. }
  81422. return -1;
  81423. };
  81424. /**
  81425. * Creater a new animation range
  81426. * @param name defines the name of the range
  81427. * @param from defines the start key
  81428. * @param to defines the end key
  81429. */
  81430. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  81431. // check name not already in use
  81432. if (!this._ranges[name]) {
  81433. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  81434. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81435. if (this.bones[i].animations[0]) {
  81436. this.bones[i].animations[0].createRange(name, from, to);
  81437. }
  81438. }
  81439. }
  81440. };
  81441. /**
  81442. * Delete a specific animation range
  81443. * @param name defines the name of the range
  81444. * @param deleteFrames defines if frames must be removed as well
  81445. */
  81446. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  81447. if (deleteFrames === void 0) { deleteFrames = true; }
  81448. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81449. if (this.bones[i].animations[0]) {
  81450. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  81451. }
  81452. }
  81453. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  81454. };
  81455. /**
  81456. * Gets a specific animation range
  81457. * @param name defines the name of the range to look for
  81458. * @returns the requested animation range or null if not found
  81459. */
  81460. Skeleton.prototype.getAnimationRange = function (name) {
  81461. return this._ranges[name];
  81462. };
  81463. /**
  81464. * Gets the list of all animation ranges defined on this skeleton
  81465. * @returns an array
  81466. */
  81467. Skeleton.prototype.getAnimationRanges = function () {
  81468. var animationRanges = [];
  81469. var name;
  81470. var i = 0;
  81471. for (name in this._ranges) {
  81472. animationRanges[i] = this._ranges[name];
  81473. i++;
  81474. }
  81475. return animationRanges;
  81476. };
  81477. /**
  81478. * Copy animation range from a source skeleton.
  81479. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  81480. * @param source defines the source skeleton
  81481. * @param name defines the name of the range to copy
  81482. * @param rescaleAsRequired defines if rescaling must be applied if required
  81483. * @returns true if operation was successful
  81484. */
  81485. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  81486. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81487. if (this._ranges[name] || !source.getAnimationRange(name)) {
  81488. return false;
  81489. }
  81490. var ret = true;
  81491. var frameOffset = this._getHighestAnimationFrame() + 1;
  81492. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  81493. var boneDict = {};
  81494. var sourceBones = source.bones;
  81495. var nBones;
  81496. var i;
  81497. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  81498. boneDict[sourceBones[i].name] = sourceBones[i];
  81499. }
  81500. if (this.bones.length !== sourceBones.length) {
  81501. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  81502. ret = false;
  81503. }
  81504. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  81505. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  81506. var boneName = this.bones[i].name;
  81507. var sourceBone = boneDict[boneName];
  81508. if (sourceBone) {
  81509. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  81510. }
  81511. else {
  81512. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  81513. ret = false;
  81514. }
  81515. }
  81516. // do not call createAnimationRange(), since it also is done to bones, which was already done
  81517. var range = source.getAnimationRange(name);
  81518. if (range) {
  81519. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  81520. }
  81521. return ret;
  81522. };
  81523. /**
  81524. * Forces the skeleton to go to rest pose
  81525. */
  81526. Skeleton.prototype.returnToRest = function () {
  81527. for (var index = 0; index < this.bones.length; index++) {
  81528. this.bones[index].returnToRest();
  81529. }
  81530. };
  81531. Skeleton.prototype._getHighestAnimationFrame = function () {
  81532. var ret = 0;
  81533. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81534. if (this.bones[i].animations[0]) {
  81535. var highest = this.bones[i].animations[0].getHighestFrame();
  81536. if (ret < highest) {
  81537. ret = highest;
  81538. }
  81539. }
  81540. }
  81541. return ret;
  81542. };
  81543. /**
  81544. * Begin a specific animation range
  81545. * @param name defines the name of the range to start
  81546. * @param loop defines if looping must be turned on (false by default)
  81547. * @param speedRatio defines the speed ratio to apply (1 by default)
  81548. * @param onAnimationEnd defines a callback which will be called when animation will end
  81549. * @returns a new animatable
  81550. */
  81551. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  81552. var range = this.getAnimationRange(name);
  81553. if (!range) {
  81554. return null;
  81555. }
  81556. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  81557. };
  81558. /** @hidden */
  81559. Skeleton.prototype._markAsDirty = function () {
  81560. this._isDirty = true;
  81561. };
  81562. /** @hidden */
  81563. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  81564. this._meshesWithPoseMatrix.push(mesh);
  81565. };
  81566. /** @hidden */
  81567. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  81568. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  81569. if (index > -1) {
  81570. this._meshesWithPoseMatrix.splice(index, 1);
  81571. }
  81572. };
  81573. /** @hidden */
  81574. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  81575. this.onBeforeComputeObservable.notifyObservers(this);
  81576. for (var index = 0; index < this.bones.length; index++) {
  81577. var bone = this.bones[index];
  81578. var parentBone = bone.getParent();
  81579. if (parentBone) {
  81580. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  81581. }
  81582. else {
  81583. if (initialSkinMatrix) {
  81584. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  81585. }
  81586. else {
  81587. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  81588. }
  81589. }
  81590. if (bone._index !== -1) {
  81591. var mappedIndex = bone._index === null ? index : bone._index;
  81592. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  81593. }
  81594. }
  81595. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  81596. };
  81597. /**
  81598. * Build all resources required to render a skeleton
  81599. */
  81600. Skeleton.prototype.prepare = function () {
  81601. if (!this._isDirty) {
  81602. return;
  81603. }
  81604. if (this.needInitialSkinMatrix) {
  81605. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  81606. var mesh = this._meshesWithPoseMatrix[index];
  81607. var poseMatrix = mesh.getPoseMatrix();
  81608. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  81609. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81610. }
  81611. if (this._synchronizedWithMesh !== mesh) {
  81612. this._synchronizedWithMesh = mesh;
  81613. // Prepare bones
  81614. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  81615. var bone = this.bones[boneIndex];
  81616. if (!bone.getParent()) {
  81617. var matrix = bone.getBaseMatrix();
  81618. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  81619. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  81620. }
  81621. }
  81622. }
  81623. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  81624. }
  81625. }
  81626. else {
  81627. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  81628. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81629. }
  81630. this._computeTransformMatrices(this._transformMatrices, null);
  81631. }
  81632. this._isDirty = false;
  81633. this._scene._activeBones.addCount(this.bones.length, false);
  81634. };
  81635. /**
  81636. * Gets the list of animatables currently running for this skeleton
  81637. * @returns an array of animatables
  81638. */
  81639. Skeleton.prototype.getAnimatables = function () {
  81640. if (!this._animatables || this._animatables.length !== this.bones.length) {
  81641. this._animatables = [];
  81642. for (var index = 0; index < this.bones.length; index++) {
  81643. this._animatables.push(this.bones[index]);
  81644. }
  81645. }
  81646. return this._animatables;
  81647. };
  81648. /**
  81649. * Clone the current skeleton
  81650. * @param name defines the name of the new skeleton
  81651. * @param id defines the id of the enw skeleton
  81652. * @returns the new skeleton
  81653. */
  81654. Skeleton.prototype.clone = function (name, id) {
  81655. var result = new Skeleton(name, id || name, this._scene);
  81656. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81657. for (var index = 0; index < this.bones.length; index++) {
  81658. var source = this.bones[index];
  81659. var parentBone = null;
  81660. var parent_1 = source.getParent();
  81661. if (parent_1) {
  81662. var parentIndex = this.bones.indexOf(parent_1);
  81663. parentBone = result.bones[parentIndex];
  81664. }
  81665. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  81666. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  81667. }
  81668. if (this._ranges) {
  81669. result._ranges = {};
  81670. for (var rangeName in this._ranges) {
  81671. var range = this._ranges[rangeName];
  81672. if (range) {
  81673. result._ranges[rangeName] = range.clone();
  81674. }
  81675. }
  81676. }
  81677. this._isDirty = true;
  81678. return result;
  81679. };
  81680. /**
  81681. * Enable animation blending for this skeleton
  81682. * @param blendingSpeed defines the blending speed to apply
  81683. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  81684. */
  81685. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  81686. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  81687. this.bones.forEach(function (bone) {
  81688. bone.animations.forEach(function (animation) {
  81689. animation.enableBlending = true;
  81690. animation.blendingSpeed = blendingSpeed;
  81691. });
  81692. });
  81693. };
  81694. /**
  81695. * Releases all resources associated with the current skeleton
  81696. */
  81697. Skeleton.prototype.dispose = function () {
  81698. this._meshesWithPoseMatrix = [];
  81699. // Animations
  81700. this.getScene().stopAnimation(this);
  81701. // Remove from scene
  81702. this.getScene().removeSkeleton(this);
  81703. };
  81704. /**
  81705. * Serialize the skeleton in a JSON object
  81706. * @returns a JSON object
  81707. */
  81708. Skeleton.prototype.serialize = function () {
  81709. var serializationObject = {};
  81710. serializationObject.name = this.name;
  81711. serializationObject.id = this.id;
  81712. if (this.dimensionsAtRest) {
  81713. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  81714. }
  81715. serializationObject.bones = [];
  81716. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81717. for (var index = 0; index < this.bones.length; index++) {
  81718. var bone = this.bones[index];
  81719. var parent_2 = bone.getParent();
  81720. var serializedBone = {
  81721. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  81722. name: bone.name,
  81723. matrix: bone.getBaseMatrix().toArray(),
  81724. rest: bone.getRestPose().toArray()
  81725. };
  81726. serializationObject.bones.push(serializedBone);
  81727. if (bone.length) {
  81728. serializedBone.length = bone.length;
  81729. }
  81730. if (bone.metadata) {
  81731. serializedBone.metadata = bone.metadata;
  81732. }
  81733. if (bone.animations && bone.animations.length > 0) {
  81734. serializedBone.animation = bone.animations[0].serialize();
  81735. }
  81736. serializationObject.ranges = [];
  81737. for (var name in this._ranges) {
  81738. var source = this._ranges[name];
  81739. if (!source) {
  81740. continue;
  81741. }
  81742. var range = {};
  81743. range.name = name;
  81744. range.from = source.from;
  81745. range.to = source.to;
  81746. serializationObject.ranges.push(range);
  81747. }
  81748. }
  81749. return serializationObject;
  81750. };
  81751. /**
  81752. * Creates a new skeleton from serialized data
  81753. * @param parsedSkeleton defines the serialized data
  81754. * @param scene defines the hosting scene
  81755. * @returns a new skeleton
  81756. */
  81757. Skeleton.Parse = function (parsedSkeleton, scene) {
  81758. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  81759. if (parsedSkeleton.dimensionsAtRest) {
  81760. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  81761. }
  81762. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  81763. var index;
  81764. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  81765. var parsedBone = parsedSkeleton.bones[index];
  81766. var parentBone = null;
  81767. if (parsedBone.parentBoneIndex > -1) {
  81768. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  81769. }
  81770. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  81771. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  81772. if (parsedBone.length) {
  81773. bone.length = parsedBone.length;
  81774. }
  81775. if (parsedBone.metadata) {
  81776. bone.metadata = parsedBone.metadata;
  81777. }
  81778. if (parsedBone.animation) {
  81779. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  81780. }
  81781. }
  81782. // placed after bones, so createAnimationRange can cascade down
  81783. if (parsedSkeleton.ranges) {
  81784. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  81785. var data = parsedSkeleton.ranges[index];
  81786. skeleton.createAnimationRange(data.name, data.from, data.to);
  81787. }
  81788. }
  81789. return skeleton;
  81790. };
  81791. /**
  81792. * Compute all node absolute transforms
  81793. * @param forceUpdate defines if computation must be done even if cache is up to date
  81794. */
  81795. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  81796. if (forceUpdate === void 0) { forceUpdate = false; }
  81797. var renderId = this._scene.getRenderId();
  81798. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  81799. this.bones[0].computeAbsoluteTransforms();
  81800. this._lastAbsoluteTransformsUpdateId = renderId;
  81801. }
  81802. };
  81803. /**
  81804. * Gets the root pose matrix
  81805. * @returns a matrix
  81806. */
  81807. Skeleton.prototype.getPoseMatrix = function () {
  81808. var poseMatrix = null;
  81809. if (this._meshesWithPoseMatrix.length > 0) {
  81810. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  81811. }
  81812. return poseMatrix;
  81813. };
  81814. /**
  81815. * Sorts bones per internal index
  81816. */
  81817. Skeleton.prototype.sortBones = function () {
  81818. var bones = new Array();
  81819. var visited = new Array(this.bones.length);
  81820. for (var index = 0; index < this.bones.length; index++) {
  81821. this._sortBones(index, bones, visited);
  81822. }
  81823. this.bones = bones;
  81824. };
  81825. Skeleton.prototype._sortBones = function (index, bones, visited) {
  81826. if (visited[index]) {
  81827. return;
  81828. }
  81829. visited[index] = true;
  81830. var bone = this.bones[index];
  81831. if (bone._index === undefined) {
  81832. bone._index = index;
  81833. }
  81834. var parentBone = bone.getParent();
  81835. if (parentBone) {
  81836. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  81837. }
  81838. bones.push(bone);
  81839. };
  81840. return Skeleton;
  81841. }());
  81842. BABYLON.Skeleton = Skeleton;
  81843. })(BABYLON || (BABYLON = {}));
  81844. //# sourceMappingURL=babylon.skeleton.js.map
  81845. var BABYLON;
  81846. (function (BABYLON) {
  81847. /**
  81848. * Class representing spherical polynomial coefficients to the 3rd degree
  81849. */
  81850. var SphericalPolynomial = /** @class */ (function () {
  81851. function SphericalPolynomial() {
  81852. /**
  81853. * The x coefficients of the spherical polynomial
  81854. */
  81855. this.x = BABYLON.Vector3.Zero();
  81856. /**
  81857. * The y coefficients of the spherical polynomial
  81858. */
  81859. this.y = BABYLON.Vector3.Zero();
  81860. /**
  81861. * The z coefficients of the spherical polynomial
  81862. */
  81863. this.z = BABYLON.Vector3.Zero();
  81864. /**
  81865. * The xx coefficients of the spherical polynomial
  81866. */
  81867. this.xx = BABYLON.Vector3.Zero();
  81868. /**
  81869. * The yy coefficients of the spherical polynomial
  81870. */
  81871. this.yy = BABYLON.Vector3.Zero();
  81872. /**
  81873. * The zz coefficients of the spherical polynomial
  81874. */
  81875. this.zz = BABYLON.Vector3.Zero();
  81876. /**
  81877. * The xy coefficients of the spherical polynomial
  81878. */
  81879. this.xy = BABYLON.Vector3.Zero();
  81880. /**
  81881. * The yz coefficients of the spherical polynomial
  81882. */
  81883. this.yz = BABYLON.Vector3.Zero();
  81884. /**
  81885. * The zx coefficients of the spherical polynomial
  81886. */
  81887. this.zx = BABYLON.Vector3.Zero();
  81888. }
  81889. /**
  81890. * Adds an ambient color to the spherical polynomial
  81891. * @param color the color to add
  81892. */
  81893. SphericalPolynomial.prototype.addAmbient = function (color) {
  81894. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81895. this.xx = this.xx.add(colorVector);
  81896. this.yy = this.yy.add(colorVector);
  81897. this.zz = this.zz.add(colorVector);
  81898. };
  81899. /**
  81900. * Scales the spherical polynomial by the given amount
  81901. * @param scale the amount to scale
  81902. */
  81903. SphericalPolynomial.prototype.scale = function (scale) {
  81904. this.x = this.x.scale(scale);
  81905. this.y = this.y.scale(scale);
  81906. this.z = this.z.scale(scale);
  81907. this.xx = this.xx.scale(scale);
  81908. this.yy = this.yy.scale(scale);
  81909. this.zz = this.zz.scale(scale);
  81910. this.yz = this.yz.scale(scale);
  81911. this.zx = this.zx.scale(scale);
  81912. this.xy = this.xy.scale(scale);
  81913. };
  81914. /**
  81915. * Gets the spherical polynomial from harmonics
  81916. * @param harmonics the spherical harmonics
  81917. * @returns the spherical polynomial
  81918. */
  81919. SphericalPolynomial.FromHarmonics = function (harmonics) {
  81920. var result = new SphericalPolynomial();
  81921. result.x = harmonics.l11.scale(1.02333);
  81922. result.y = harmonics.l1_1.scale(1.02333);
  81923. result.z = harmonics.l10.scale(1.02333);
  81924. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  81925. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  81926. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  81927. result.yz = harmonics.l2_1.scale(0.858086);
  81928. result.zx = harmonics.l21.scale(0.858086);
  81929. result.xy = harmonics.l2_2.scale(0.858086);
  81930. result.scale(1.0 / Math.PI);
  81931. return result;
  81932. };
  81933. /**
  81934. * Constructs a spherical polynomial from an array.
  81935. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  81936. * @returns the spherical polynomial
  81937. */
  81938. SphericalPolynomial.FromArray = function (data) {
  81939. var sp = new SphericalPolynomial();
  81940. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  81941. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  81942. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  81943. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  81944. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  81945. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  81946. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  81947. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  81948. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  81949. return sp;
  81950. };
  81951. return SphericalPolynomial;
  81952. }());
  81953. BABYLON.SphericalPolynomial = SphericalPolynomial;
  81954. /**
  81955. * Class representing spherical harmonics coefficients to the 3rd degree
  81956. */
  81957. var SphericalHarmonics = /** @class */ (function () {
  81958. function SphericalHarmonics() {
  81959. /**
  81960. * The l0,0 coefficients of the spherical harmonics
  81961. */
  81962. this.l00 = BABYLON.Vector3.Zero();
  81963. /**
  81964. * The l1,-1 coefficients of the spherical harmonics
  81965. */
  81966. this.l1_1 = BABYLON.Vector3.Zero();
  81967. /**
  81968. * The l1,0 coefficients of the spherical harmonics
  81969. */
  81970. this.l10 = BABYLON.Vector3.Zero();
  81971. /**
  81972. * The l1,1 coefficients of the spherical harmonics
  81973. */
  81974. this.l11 = BABYLON.Vector3.Zero();
  81975. /**
  81976. * The l2,-2 coefficients of the spherical harmonics
  81977. */
  81978. this.l2_2 = BABYLON.Vector3.Zero();
  81979. /**
  81980. * The l2,-1 coefficients of the spherical harmonics
  81981. */
  81982. this.l2_1 = BABYLON.Vector3.Zero();
  81983. /**
  81984. * The l2,0 coefficients of the spherical harmonics
  81985. */
  81986. this.l20 = BABYLON.Vector3.Zero();
  81987. /**
  81988. * The l2,1 coefficients of the spherical harmonics
  81989. */
  81990. this.l21 = BABYLON.Vector3.Zero();
  81991. /**
  81992. * The l2,2 coefficients of the spherical harmonics
  81993. */
  81994. this.lL22 = BABYLON.Vector3.Zero();
  81995. }
  81996. /**
  81997. * Adds a light to the spherical harmonics
  81998. * @param direction the direction of the light
  81999. * @param color the color of the light
  82000. * @param deltaSolidAngle the delta solid angle of the light
  82001. */
  82002. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  82003. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  82004. var c = colorVector.scale(deltaSolidAngle);
  82005. this.l00 = this.l00.add(c.scale(0.282095));
  82006. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  82007. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  82008. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  82009. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  82010. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  82011. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  82012. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  82013. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  82014. };
  82015. /**
  82016. * Scales the spherical harmonics by the given amount
  82017. * @param scale the amount to scale
  82018. */
  82019. SphericalHarmonics.prototype.scale = function (scale) {
  82020. this.l00 = this.l00.scale(scale);
  82021. this.l1_1 = this.l1_1.scale(scale);
  82022. this.l10 = this.l10.scale(scale);
  82023. this.l11 = this.l11.scale(scale);
  82024. this.l2_2 = this.l2_2.scale(scale);
  82025. this.l2_1 = this.l2_1.scale(scale);
  82026. this.l20 = this.l20.scale(scale);
  82027. this.l21 = this.l21.scale(scale);
  82028. this.lL22 = this.lL22.scale(scale);
  82029. };
  82030. /**
  82031. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  82032. *
  82033. * ```
  82034. * E_lm = A_l * L_lm
  82035. * ```
  82036. *
  82037. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  82038. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  82039. * the scaling factors are given in equation 9.
  82040. */
  82041. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  82042. // Constant (Band 0)
  82043. this.l00 = this.l00.scale(3.141593);
  82044. // Linear (Band 1)
  82045. this.l1_1 = this.l1_1.scale(2.094395);
  82046. this.l10 = this.l10.scale(2.094395);
  82047. this.l11 = this.l11.scale(2.094395);
  82048. // Quadratic (Band 2)
  82049. this.l2_2 = this.l2_2.scale(0.785398);
  82050. this.l2_1 = this.l2_1.scale(0.785398);
  82051. this.l20 = this.l20.scale(0.785398);
  82052. this.l21 = this.l21.scale(0.785398);
  82053. this.lL22 = this.lL22.scale(0.785398);
  82054. };
  82055. /**
  82056. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  82057. *
  82058. * ```
  82059. * L = (1/pi) * E * rho
  82060. * ```
  82061. *
  82062. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  82063. */
  82064. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  82065. this.scale(1.0 / Math.PI);
  82066. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  82067. // (The pixel shader must apply albedo after texture fetches, etc).
  82068. };
  82069. /**
  82070. * Gets the spherical harmonics from polynomial
  82071. * @param polynomial the spherical polynomial
  82072. * @returns the spherical harmonics
  82073. */
  82074. SphericalHarmonics.FromPolynomial = function (polynomial) {
  82075. var result = new SphericalHarmonics();
  82076. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  82077. result.l1_1 = polynomial.y.scale(0.977204);
  82078. result.l10 = polynomial.z.scale(0.977204);
  82079. result.l11 = polynomial.x.scale(0.977204);
  82080. result.l2_2 = polynomial.xy.scale(1.16538);
  82081. result.l2_1 = polynomial.yz.scale(1.16538);
  82082. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  82083. result.l21 = polynomial.zx.scale(1.16538);
  82084. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  82085. result.scale(Math.PI);
  82086. return result;
  82087. };
  82088. /**
  82089. * Constructs a spherical harmonics from an array.
  82090. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  82091. * @returns the spherical harmonics
  82092. */
  82093. SphericalHarmonics.FromArray = function (data) {
  82094. var sh = new SphericalHarmonics();
  82095. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  82096. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  82097. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  82098. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  82099. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  82100. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  82101. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  82102. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  82103. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  82104. return sh;
  82105. };
  82106. return SphericalHarmonics;
  82107. }());
  82108. BABYLON.SphericalHarmonics = SphericalHarmonics;
  82109. })(BABYLON || (BABYLON = {}));
  82110. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  82111. var BABYLON;
  82112. (function (BABYLON) {
  82113. var FileFaceOrientation = /** @class */ (function () {
  82114. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  82115. this.name = name;
  82116. this.worldAxisForNormal = worldAxisForNormal;
  82117. this.worldAxisForFileX = worldAxisForFileX;
  82118. this.worldAxisForFileY = worldAxisForFileY;
  82119. }
  82120. return FileFaceOrientation;
  82121. }());
  82122. ;
  82123. /**
  82124. * Helper class dealing with the extraction of spherical polynomial dataArray
  82125. * from a cube map.
  82126. */
  82127. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  82128. function CubeMapToSphericalPolynomialTools() {
  82129. }
  82130. /**
  82131. * Converts a texture to the according Spherical Polynomial data.
  82132. * This extracts the first 3 orders only as they are the only one used in the lighting.
  82133. *
  82134. * @param texture The texture to extract the information from.
  82135. * @return The Spherical Polynomial data.
  82136. */
  82137. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  82138. if (!texture.isCube) {
  82139. // Only supports cube Textures currently.
  82140. return null;
  82141. }
  82142. var size = texture.getSize().width;
  82143. var right = texture.readPixels(0);
  82144. var left = texture.readPixels(1);
  82145. var up;
  82146. var down;
  82147. if (texture.isRenderTarget) {
  82148. up = texture.readPixels(3);
  82149. down = texture.readPixels(2);
  82150. }
  82151. else {
  82152. up = texture.readPixels(2);
  82153. down = texture.readPixels(3);
  82154. }
  82155. var front = texture.readPixels(4);
  82156. var back = texture.readPixels(5);
  82157. var gammaSpace = texture.gammaSpace;
  82158. // Always read as RGBA.
  82159. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82160. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82161. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  82162. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82163. }
  82164. var cubeInfo = {
  82165. size: size,
  82166. right: right,
  82167. left: left,
  82168. up: up,
  82169. down: down,
  82170. front: front,
  82171. back: back,
  82172. format: format,
  82173. type: type,
  82174. gammaSpace: gammaSpace,
  82175. };
  82176. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  82177. };
  82178. /**
  82179. * Converts a cubemap to the according Spherical Polynomial data.
  82180. * This extracts the first 3 orders only as they are the only one used in the lighting.
  82181. *
  82182. * @param cubeInfo The Cube map to extract the information from.
  82183. * @return The Spherical Polynomial data.
  82184. */
  82185. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  82186. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  82187. var totalSolidAngle = 0.0;
  82188. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  82189. var du = 2.0 / cubeInfo.size;
  82190. var dv = du;
  82191. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  82192. var minUV = du * 0.5 - 1.0;
  82193. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  82194. var fileFace = this.FileFaces[faceIndex];
  82195. var dataArray = cubeInfo[fileFace.name];
  82196. var v = minUV;
  82197. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  82198. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  82199. // Because SP is still linear, so summation is fine in that basis.
  82200. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  82201. for (var y = 0; y < cubeInfo.size; y++) {
  82202. var u = minUV;
  82203. for (var x = 0; x < cubeInfo.size; x++) {
  82204. // World direction (not normalised)
  82205. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  82206. worldDirection.normalize();
  82207. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  82208. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  82209. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  82210. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  82211. // Handle Integer types.
  82212. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  82213. r /= 255;
  82214. g /= 255;
  82215. b /= 255;
  82216. }
  82217. // Handle Gamma space textures.
  82218. if (cubeInfo.gammaSpace) {
  82219. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  82220. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  82221. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  82222. }
  82223. var color = new BABYLON.Color3(r, g, b);
  82224. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  82225. totalSolidAngle += deltaSolidAngle;
  82226. u += du;
  82227. }
  82228. v += dv;
  82229. }
  82230. }
  82231. // Solid angle for entire sphere is 4*pi
  82232. var sphereSolidAngle = 4.0 * Math.PI;
  82233. // Adjust the solid angle to allow for how many faces we processed.
  82234. var facesProcessed = 6.0;
  82235. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  82236. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  82237. // This is needed because the numerical integration over the cube uses a
  82238. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  82239. // and also to compensate for accumulative error due to float precision in the summation.
  82240. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  82241. sphericalHarmonics.scale(correctionFactor);
  82242. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  82243. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  82244. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  82245. };
  82246. CubeMapToSphericalPolynomialTools.FileFaces = [
  82247. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  82248. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  82249. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  82250. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  82251. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  82252. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  82253. ];
  82254. return CubeMapToSphericalPolynomialTools;
  82255. }());
  82256. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  82257. })(BABYLON || (BABYLON = {}));
  82258. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  82259. var BABYLON;
  82260. (function (BABYLON) {
  82261. /**
  82262. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  82263. */
  82264. var PanoramaToCubeMapTools = /** @class */ (function () {
  82265. function PanoramaToCubeMapTools() {
  82266. }
  82267. /**
  82268. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  82269. *
  82270. * @param float32Array The source data.
  82271. * @param inputWidth The width of the input panorama.
  82272. * @param inputhHeight The height of the input panorama.
  82273. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  82274. * @return The cubemap data
  82275. */
  82276. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  82277. if (!float32Array) {
  82278. throw "ConvertPanoramaToCubemap: input cannot be null";
  82279. }
  82280. if (float32Array.length != inputWidth * inputHeight * 3) {
  82281. throw "ConvertPanoramaToCubemap: input size is wrong";
  82282. }
  82283. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  82284. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  82285. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  82286. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  82287. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  82288. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  82289. return {
  82290. front: textureFront,
  82291. back: textureBack,
  82292. left: textureLeft,
  82293. right: textureRight,
  82294. up: textureUp,
  82295. down: textureDown,
  82296. size: size,
  82297. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  82298. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  82299. gammaSpace: false,
  82300. };
  82301. };
  82302. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  82303. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  82304. var textureArray = new Float32Array(buffer);
  82305. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  82306. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  82307. var dy = 1 / texSize;
  82308. var fy = 0;
  82309. for (var y = 0; y < texSize; y++) {
  82310. var xv1 = faceData[0];
  82311. var xv2 = faceData[2];
  82312. for (var x = 0; x < texSize; x++) {
  82313. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  82314. v.normalize();
  82315. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  82316. // 3 channels per pixels
  82317. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  82318. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  82319. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  82320. xv1 = xv1.add(rotDX1);
  82321. xv2 = xv2.add(rotDX2);
  82322. }
  82323. fy += dy;
  82324. }
  82325. return textureArray;
  82326. };
  82327. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  82328. var theta = Math.atan2(vDir.z, vDir.x);
  82329. var phi = Math.acos(vDir.y);
  82330. while (theta < -Math.PI)
  82331. theta += 2 * Math.PI;
  82332. while (theta > Math.PI)
  82333. theta -= 2 * Math.PI;
  82334. var dx = theta / Math.PI;
  82335. var dy = phi / Math.PI;
  82336. // recenter.
  82337. dx = dx * 0.5 + 0.5;
  82338. var px = Math.round(dx * inputWidth);
  82339. if (px < 0)
  82340. px = 0;
  82341. else if (px >= inputWidth)
  82342. px = inputWidth - 1;
  82343. var py = Math.round(dy * inputHeight);
  82344. if (py < 0)
  82345. py = 0;
  82346. else if (py >= inputHeight)
  82347. py = inputHeight - 1;
  82348. var inputY = (inputHeight - py - 1);
  82349. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  82350. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  82351. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  82352. return {
  82353. r: r,
  82354. g: g,
  82355. b: b
  82356. };
  82357. };
  82358. PanoramaToCubeMapTools.FACE_FRONT = [
  82359. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82360. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82361. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82362. new BABYLON.Vector3(1.0, 1.0, -1.0)
  82363. ];
  82364. PanoramaToCubeMapTools.FACE_BACK = [
  82365. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82366. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82367. new BABYLON.Vector3(1.0, 1.0, 1.0),
  82368. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  82369. ];
  82370. PanoramaToCubeMapTools.FACE_RIGHT = [
  82371. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82372. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82373. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82374. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82375. ];
  82376. PanoramaToCubeMapTools.FACE_LEFT = [
  82377. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82378. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82379. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82380. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  82381. ];
  82382. PanoramaToCubeMapTools.FACE_DOWN = [
  82383. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82384. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82385. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82386. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82387. ];
  82388. PanoramaToCubeMapTools.FACE_UP = [
  82389. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82390. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82391. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82392. new BABYLON.Vector3(1.0, -1.0, -1.0)
  82393. ];
  82394. return PanoramaToCubeMapTools;
  82395. }());
  82396. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  82397. })(BABYLON || (BABYLON = {}));
  82398. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  82399. var BABYLON;
  82400. (function (BABYLON) {
  82401. ;
  82402. /**
  82403. * This groups tools to convert HDR texture to native colors array.
  82404. */
  82405. var HDRTools = /** @class */ (function () {
  82406. function HDRTools() {
  82407. }
  82408. HDRTools.Ldexp = function (mantissa, exponent) {
  82409. if (exponent > 1023) {
  82410. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  82411. }
  82412. if (exponent < -1074) {
  82413. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  82414. }
  82415. return mantissa * Math.pow(2, exponent);
  82416. };
  82417. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  82418. if (exponent > 0) { /*nonzero pixel*/
  82419. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  82420. float32array[index + 0] = red * exponent;
  82421. float32array[index + 1] = green * exponent;
  82422. float32array[index + 2] = blue * exponent;
  82423. }
  82424. else {
  82425. float32array[index + 0] = 0;
  82426. float32array[index + 1] = 0;
  82427. float32array[index + 2] = 0;
  82428. }
  82429. };
  82430. HDRTools.readStringLine = function (uint8array, startIndex) {
  82431. var line = "";
  82432. var character = "";
  82433. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  82434. character = String.fromCharCode(uint8array[i]);
  82435. if (character == "\n") {
  82436. break;
  82437. }
  82438. line += character;
  82439. }
  82440. return line;
  82441. };
  82442. /**
  82443. * Reads header information from an RGBE texture stored in a native array.
  82444. * More information on this format are available here:
  82445. * https://en.wikipedia.org/wiki/RGBE_image_format
  82446. *
  82447. * @param uint8array The binary file stored in native array.
  82448. * @return The header information.
  82449. */
  82450. HDRTools.RGBE_ReadHeader = function (uint8array) {
  82451. var height = 0;
  82452. var width = 0;
  82453. var line = this.readStringLine(uint8array, 0);
  82454. if (line[0] != '#' || line[1] != '?') {
  82455. throw "Bad HDR Format.";
  82456. }
  82457. var endOfHeader = false;
  82458. var findFormat = false;
  82459. var lineIndex = 0;
  82460. do {
  82461. lineIndex += (line.length + 1);
  82462. line = this.readStringLine(uint8array, lineIndex);
  82463. if (line == "FORMAT=32-bit_rle_rgbe") {
  82464. findFormat = true;
  82465. }
  82466. else if (line.length == 0) {
  82467. endOfHeader = true;
  82468. }
  82469. } while (!endOfHeader);
  82470. if (!findFormat) {
  82471. throw "HDR Bad header format, unsupported FORMAT";
  82472. }
  82473. lineIndex += (line.length + 1);
  82474. line = this.readStringLine(uint8array, lineIndex);
  82475. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  82476. var match = sizeRegexp.exec(line);
  82477. // TODO. Support +Y and -X if needed.
  82478. if (!match || match.length < 3) {
  82479. throw "HDR Bad header format, no size";
  82480. }
  82481. width = parseInt(match[2]);
  82482. height = parseInt(match[1]);
  82483. if (width < 8 || width > 0x7fff) {
  82484. throw "HDR Bad header format, unsupported size";
  82485. }
  82486. lineIndex += (line.length + 1);
  82487. return {
  82488. height: height,
  82489. width: width,
  82490. dataPosition: lineIndex
  82491. };
  82492. };
  82493. /**
  82494. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  82495. * This RGBE texture needs to store the information as a panorama.
  82496. *
  82497. * More information on this format are available here:
  82498. * https://en.wikipedia.org/wiki/RGBE_image_format
  82499. *
  82500. * @param buffer The binary file stored in an array buffer.
  82501. * @param size The expected size of the extracted cubemap.
  82502. * @return The Cube Map information.
  82503. */
  82504. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  82505. var uint8array = new Uint8Array(buffer);
  82506. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  82507. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82508. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  82509. return cubeMapData;
  82510. };
  82511. /**
  82512. * Returns the pixels data extracted from an RGBE texture.
  82513. * This pixels will be stored left to right up to down in the R G B order in one array.
  82514. *
  82515. * More information on this format are available here:
  82516. * https://en.wikipedia.org/wiki/RGBE_image_format
  82517. *
  82518. * @param uint8array The binary file stored in an array buffer.
  82519. * @param hdrInfo The header information of the file.
  82520. * @return The pixels data in RGB right to left up to down order.
  82521. */
  82522. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  82523. // Keep for multi format supports.
  82524. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82525. };
  82526. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  82527. var num_scanlines = hdrInfo.height;
  82528. var scanline_width = hdrInfo.width;
  82529. var a, b, c, d, count;
  82530. var dataIndex = hdrInfo.dataPosition;
  82531. var index = 0, endIndex = 0, i = 0;
  82532. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  82533. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  82534. // 3 channels of 4 bytes per pixel in float.
  82535. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  82536. var resultArray = new Float32Array(resultBuffer);
  82537. // read in each successive scanline
  82538. while (num_scanlines > 0) {
  82539. a = uint8array[dataIndex++];
  82540. b = uint8array[dataIndex++];
  82541. c = uint8array[dataIndex++];
  82542. d = uint8array[dataIndex++];
  82543. if (a != 2 || b != 2 || (c & 0x80)) {
  82544. // this file is not run length encoded
  82545. throw "HDR Bad header format, not RLE";
  82546. }
  82547. if (((c << 8) | d) != scanline_width) {
  82548. throw "HDR Bad header format, wrong scan line width";
  82549. }
  82550. index = 0;
  82551. // read each of the four channels for the scanline into the buffer
  82552. for (i = 0; i < 4; i++) {
  82553. endIndex = (i + 1) * scanline_width;
  82554. while (index < endIndex) {
  82555. a = uint8array[dataIndex++];
  82556. b = uint8array[dataIndex++];
  82557. if (a > 128) {
  82558. // a run of the same value
  82559. count = a - 128;
  82560. if ((count == 0) || (count > endIndex - index)) {
  82561. throw "HDR Bad Format, bad scanline data (run)";
  82562. }
  82563. while (count-- > 0) {
  82564. scanLineArray[index++] = b;
  82565. }
  82566. }
  82567. else {
  82568. // a non-run
  82569. count = a;
  82570. if ((count == 0) || (count > endIndex - index)) {
  82571. throw "HDR Bad Format, bad scanline data (non-run)";
  82572. }
  82573. scanLineArray[index++] = b;
  82574. if (--count > 0) {
  82575. for (var j = 0; j < count; j++) {
  82576. scanLineArray[index++] = uint8array[dataIndex++];
  82577. }
  82578. }
  82579. }
  82580. }
  82581. }
  82582. // now convert data from buffer into floats
  82583. for (i = 0; i < scanline_width; i++) {
  82584. a = scanLineArray[i];
  82585. b = scanLineArray[i + scanline_width];
  82586. c = scanLineArray[i + 2 * scanline_width];
  82587. d = scanLineArray[i + 3 * scanline_width];
  82588. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  82589. }
  82590. num_scanlines--;
  82591. }
  82592. return resultArray;
  82593. };
  82594. return HDRTools;
  82595. }());
  82596. BABYLON.HDRTools = HDRTools;
  82597. })(BABYLON || (BABYLON = {}));
  82598. //# sourceMappingURL=babylon.hdr.js.map
  82599. var BABYLON;
  82600. (function (BABYLON) {
  82601. /**
  82602. * Sets of helpers addressing the serialization and deserialization of environment texture
  82603. * stored in a BabylonJS env file.
  82604. * Those files are usually stored as .env files.
  82605. */
  82606. var EnvironmentTextureTools = /** @class */ (function () {
  82607. function EnvironmentTextureTools() {
  82608. }
  82609. /**
  82610. * Gets the environment info from an env file.
  82611. * @param data The array buffer containing the .env bytes.
  82612. * @returns the environment file info (the json header) if successfully parsed.
  82613. */
  82614. EnvironmentTextureTools.GetEnvInfo = function (data) {
  82615. var dataView = new DataView(data);
  82616. var pos = 0;
  82617. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82618. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  82619. BABYLON.Tools.Error('Not a babylon environment map');
  82620. return null;
  82621. }
  82622. }
  82623. // Read json manifest - collect characters up to null terminator
  82624. var manifestString = '';
  82625. var charCode = 0x00;
  82626. while ((charCode = dataView.getUint8(pos++))) {
  82627. manifestString += String.fromCharCode(charCode);
  82628. }
  82629. var manifest = JSON.parse(manifestString);
  82630. if (manifest.specular) {
  82631. // Extend the header with the position of the payload.
  82632. manifest.specular.specularDataPosition = pos;
  82633. }
  82634. return manifest;
  82635. };
  82636. /**
  82637. * Creates an environment texture from a loaded cube texture.
  82638. * @param texture defines the cube texture to convert in env file
  82639. * @return a promise containing the environment data if succesfull.
  82640. */
  82641. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  82642. var _this = this;
  82643. var internalTexture = texture.getInternalTexture();
  82644. if (!internalTexture) {
  82645. return Promise.reject("The cube texture is invalid.");
  82646. }
  82647. if (!texture._prefiltered) {
  82648. return Promise.reject("The cube texture is invalid (not prefiltered).");
  82649. }
  82650. var engine = internalTexture.getEngine();
  82651. if (engine && engine.premultipliedAlpha) {
  82652. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  82653. }
  82654. var canvas = engine.getRenderingCanvas();
  82655. if (!canvas) {
  82656. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  82657. }
  82658. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82659. if (!engine.getCaps().textureFloatRender) {
  82660. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82661. if (!engine.getCaps().textureHalfFloatRender) {
  82662. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  82663. }
  82664. }
  82665. var cubeWidth = internalTexture.width;
  82666. var hostingScene = new BABYLON.Scene(engine);
  82667. var specularTextures = {};
  82668. var promises = [];
  82669. // Read and collect all mipmaps data from the cube.
  82670. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  82671. mipmapsCount = Math.round(mipmapsCount);
  82672. var _loop_1 = function (i) {
  82673. var faceWidth = Math.pow(2, mipmapsCount - i);
  82674. var _loop_2 = function (face) {
  82675. var data = texture.readPixels(face, i);
  82676. // Creates a temp texture with the face data.
  82677. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  82678. // And rgbdEncode them.
  82679. var promise = new Promise(function (resolve, reject) {
  82680. 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);
  82681. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82682. rgbdPostProcess.onApply = function (effect) {
  82683. effect._bindTexture("textureSampler", tempTexture);
  82684. };
  82685. // As the process needs to happen on the main canvas, keep track of the current size
  82686. var currentW = engine.getRenderWidth();
  82687. var currentH = engine.getRenderHeight();
  82688. // Set the desired size for the texture
  82689. engine.setSize(faceWidth, faceWidth);
  82690. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  82691. // Reading datas from WebGL
  82692. BABYLON.Tools.ToBlob(canvas, function (blob) {
  82693. var fileReader = new FileReader();
  82694. fileReader.onload = function (event) {
  82695. var arrayBuffer = event.target.result;
  82696. specularTextures[i * 6 + face] = arrayBuffer;
  82697. resolve();
  82698. };
  82699. fileReader.readAsArrayBuffer(blob);
  82700. });
  82701. // Reapply the previous canvas size
  82702. engine.setSize(currentW, currentH);
  82703. });
  82704. });
  82705. promises.push(promise);
  82706. };
  82707. // All faces of the cube.
  82708. for (var face = 0; face < 6; face++) {
  82709. _loop_2(face);
  82710. }
  82711. };
  82712. for (var i = 0; i <= mipmapsCount; i++) {
  82713. _loop_1(i);
  82714. }
  82715. // Once all the textures haves been collected as RGBD stored in PNGs
  82716. return Promise.all(promises).then(function () {
  82717. // We can delete the hosting scene keeping track of all the creation objects
  82718. hostingScene.dispose();
  82719. // Creates the json header for the env texture
  82720. var info = {
  82721. version: 1,
  82722. width: cubeWidth,
  82723. irradiance: _this._CreateEnvTextureIrradiance(texture),
  82724. specular: {
  82725. mipmaps: []
  82726. }
  82727. };
  82728. // Sets the specular image data information
  82729. var position = 0;
  82730. for (var i = 0; i <= mipmapsCount; i++) {
  82731. for (var face = 0; face < 6; face++) {
  82732. var byteLength = specularTextures[i * 6 + face].byteLength;
  82733. info.specular.mipmaps.push({
  82734. length: byteLength,
  82735. position: position
  82736. });
  82737. position += byteLength;
  82738. }
  82739. }
  82740. // Encode the JSON as an array buffer
  82741. var infoString = JSON.stringify(info);
  82742. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  82743. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  82744. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  82745. infoView[i] = infoString.charCodeAt(i);
  82746. }
  82747. // Ends up with a null terminator for easier parsing
  82748. infoView[infoString.length] = 0x00;
  82749. // Computes the final required size and creates the storage
  82750. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  82751. var finalBuffer = new ArrayBuffer(totalSize);
  82752. var finalBufferView = new Uint8Array(finalBuffer);
  82753. var dataView = new DataView(finalBuffer);
  82754. // Copy the magic bytes identifying the file in
  82755. var pos = 0;
  82756. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82757. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  82758. }
  82759. // Add the json info
  82760. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  82761. pos += infoBuffer.byteLength;
  82762. // Finally inserts the texture data
  82763. for (var i = 0; i <= mipmapsCount; i++) {
  82764. for (var face = 0; face < 6; face++) {
  82765. var dataBuffer = specularTextures[i * 6 + face];
  82766. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  82767. pos += dataBuffer.byteLength;
  82768. }
  82769. }
  82770. // Voila
  82771. return finalBuffer;
  82772. });
  82773. };
  82774. /**
  82775. * Creates a JSON representation of the spherical data.
  82776. * @param texture defines the texture containing the polynomials
  82777. * @return the JSON representation of the spherical info
  82778. */
  82779. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  82780. var polynmials = texture.sphericalPolynomial;
  82781. if (polynmials == null) {
  82782. return null;
  82783. }
  82784. return {
  82785. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  82786. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  82787. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  82788. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  82789. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  82790. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  82791. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  82792. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  82793. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  82794. };
  82795. };
  82796. /**
  82797. * Uploads the texture info contained in the env file to the GPU.
  82798. * @param texture defines the internal texture to upload to
  82799. * @param arrayBuffer defines the buffer cotaining the data to load
  82800. * @param info defines the texture info retrieved through the GetEnvInfo method
  82801. * @returns a promise
  82802. */
  82803. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  82804. if (info.version !== 1) {
  82805. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82806. }
  82807. var specularInfo = info.specular;
  82808. if (!specularInfo) {
  82809. // Nothing else parsed so far
  82810. return Promise.resolve();
  82811. }
  82812. // Double checks the enclosed info
  82813. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  82814. mipmapsCount = Math.round(mipmapsCount) + 1;
  82815. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  82816. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  82817. }
  82818. var imageData = new Array(mipmapsCount);
  82819. for (var i = 0; i < mipmapsCount; i++) {
  82820. imageData[i] = new Array(6);
  82821. for (var face = 0; face < 6; face++) {
  82822. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  82823. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  82824. }
  82825. }
  82826. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  82827. };
  82828. /**
  82829. * Uploads the levels of image data to the GPU.
  82830. * @param texture defines the internal texture to upload to
  82831. * @param imageData defines the array buffer views of image data [mipmap][face]
  82832. * @returns a promise
  82833. */
  82834. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  82835. var mipmapsCount = imageData.length;
  82836. // Gets everything ready.
  82837. var engine = texture.getEngine();
  82838. var expandTexture = false;
  82839. var generateNonLODTextures = false;
  82840. var rgbdPostProcess = null;
  82841. var cubeRtt = null;
  82842. var lodTextures = null;
  82843. var caps = engine.getCaps();
  82844. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82845. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82846. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82847. // Add extra process if texture lod is not supported
  82848. if (!caps.textureLOD) {
  82849. expandTexture = false;
  82850. generateNonLODTextures = true;
  82851. lodTextures = {};
  82852. }
  82853. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  82854. else if (engine.webGLVersion < 2) {
  82855. expandTexture = false;
  82856. }
  82857. // If half float available we can uncompress the texture
  82858. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  82859. expandTexture = true;
  82860. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82861. }
  82862. // If full float available we can uncompress the texture
  82863. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  82864. expandTexture = true;
  82865. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82866. }
  82867. // Expand the texture if possible
  82868. if (expandTexture) {
  82869. // Simply run through the decode PP
  82870. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  82871. texture._isRGBD = false;
  82872. texture.invertY = false;
  82873. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  82874. generateDepthBuffer: false,
  82875. generateMipMaps: true,
  82876. generateStencilBuffer: false,
  82877. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  82878. type: texture.type,
  82879. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  82880. });
  82881. }
  82882. else {
  82883. texture._isRGBD = true;
  82884. texture.invertY = true;
  82885. // In case of missing support, applies the same patch than DDS files.
  82886. if (generateNonLODTextures) {
  82887. var mipSlices = 3;
  82888. var scale = texture._lodGenerationScale;
  82889. var offset = texture._lodGenerationOffset;
  82890. for (var i = 0; i < mipSlices; i++) {
  82891. //compute LOD from even spacing in smoothness (matching shader calculation)
  82892. var smoothness = i / (mipSlices - 1);
  82893. var roughness = 1 - smoothness;
  82894. var minLODIndex = offset; // roughness = 0
  82895. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  82896. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  82897. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  82898. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  82899. glTextureFromLod.isCube = true;
  82900. glTextureFromLod.invertY = true;
  82901. glTextureFromLod.generateMipMaps = false;
  82902. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  82903. // Wrap in a base texture for easy binding.
  82904. var lodTexture = new BABYLON.BaseTexture(null);
  82905. lodTexture.isCube = true;
  82906. lodTexture._texture = glTextureFromLod;
  82907. lodTextures[mipmapIndex] = lodTexture;
  82908. switch (i) {
  82909. case 0:
  82910. texture._lodTextureLow = lodTexture;
  82911. break;
  82912. case 1:
  82913. texture._lodTextureMid = lodTexture;
  82914. break;
  82915. case 2:
  82916. texture._lodTextureHigh = lodTexture;
  82917. break;
  82918. }
  82919. }
  82920. }
  82921. }
  82922. var promises = [];
  82923. var _loop_3 = function (i) {
  82924. var _loop_4 = function (face) {
  82925. // Constructs an image element from image data
  82926. var bytes = imageData[i][face];
  82927. var blob = new Blob([bytes], { type: 'image/png' });
  82928. var url = URL.createObjectURL(blob);
  82929. var image = new Image();
  82930. image.src = url;
  82931. // Enqueue promise to upload to the texture.
  82932. var promise = new Promise(function (resolve, reject) {
  82933. image.onload = function () {
  82934. if (expandTexture) {
  82935. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  82936. reject(message);
  82937. }, image);
  82938. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82939. // Uncompress the data to a RTT
  82940. rgbdPostProcess.onApply = function (effect) {
  82941. effect._bindTexture("textureSampler", tempTexture_1);
  82942. effect.setFloat2("scale", 1, 1);
  82943. };
  82944. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  82945. // Cleanup
  82946. engine.restoreDefaultFramebuffer();
  82947. tempTexture_1.dispose();
  82948. window.URL.revokeObjectURL(url);
  82949. resolve();
  82950. });
  82951. }
  82952. else {
  82953. engine._uploadImageToTexture(texture, image, face, i);
  82954. // Upload the face to the none lod texture support
  82955. if (generateNonLODTextures) {
  82956. var lodTexture = lodTextures[i];
  82957. if (lodTexture) {
  82958. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  82959. }
  82960. }
  82961. resolve();
  82962. }
  82963. };
  82964. image.onerror = function (error) {
  82965. reject(error);
  82966. };
  82967. });
  82968. promises.push(promise);
  82969. };
  82970. // All faces
  82971. for (var face = 0; face < 6; face++) {
  82972. _loop_4(face);
  82973. }
  82974. };
  82975. // All mipmaps
  82976. for (var i = 0; i < mipmapsCount; i++) {
  82977. _loop_3(i);
  82978. }
  82979. // Once all done, finishes the cleanup and return
  82980. return Promise.all(promises).then(function () {
  82981. // Relase temp RTT.
  82982. if (cubeRtt) {
  82983. engine._releaseFramebufferObjects(cubeRtt);
  82984. cubeRtt._swapAndDie(texture);
  82985. }
  82986. // Relase temp Post Process.
  82987. if (rgbdPostProcess) {
  82988. rgbdPostProcess.dispose();
  82989. }
  82990. // Flag internal texture as ready in case they are in use.
  82991. if (generateNonLODTextures) {
  82992. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  82993. texture._lodTextureHigh._texture.isReady = true;
  82994. }
  82995. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  82996. texture._lodTextureMid._texture.isReady = true;
  82997. }
  82998. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  82999. texture._lodTextureLow._texture.isReady = true;
  83000. }
  83001. }
  83002. });
  83003. };
  83004. /**
  83005. * Uploads spherical polynomials information to the texture.
  83006. * @param texture defines the texture we are trying to upload the information to
  83007. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  83008. */
  83009. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  83010. if (info.version !== 1) {
  83011. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  83012. }
  83013. var irradianceInfo = info.irradiance;
  83014. if (!irradianceInfo) {
  83015. return;
  83016. }
  83017. var sp = new BABYLON.SphericalPolynomial();
  83018. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  83019. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  83020. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  83021. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  83022. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  83023. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  83024. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  83025. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  83026. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  83027. texture._sphericalPolynomial = sp;
  83028. };
  83029. /**
  83030. * Magic number identifying the env file.
  83031. */
  83032. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  83033. return EnvironmentTextureTools;
  83034. }());
  83035. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  83036. })(BABYLON || (BABYLON = {}));
  83037. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  83038. var BABYLON;
  83039. (function (BABYLON) {
  83040. /**
  83041. * This represents a texture coming from an HDR input.
  83042. *
  83043. * The only supported format is currently panorama picture stored in RGBE format.
  83044. * Example of such files can be found on HDRLib: http://hdrlib.com/
  83045. */
  83046. var HDRCubeTexture = /** @class */ (function (_super) {
  83047. __extends(HDRCubeTexture, _super);
  83048. /**
  83049. * Instantiates an HDRTexture from the following parameters.
  83050. *
  83051. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  83052. * @param scene The scene the texture will be used in
  83053. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  83054. * @param noMipmap Forces to not generate the mipmap if true
  83055. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  83056. * @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)
  83057. * @param reserved Reserved flag for internal use.
  83058. */
  83059. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  83060. if (noMipmap === void 0) { noMipmap = false; }
  83061. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83062. if (gammaSpace === void 0) { gammaSpace = false; }
  83063. if (reserved === void 0) { reserved = false; }
  83064. if (onLoad === void 0) { onLoad = null; }
  83065. if (onError === void 0) { onError = null; }
  83066. var _this = _super.call(this, scene) || this;
  83067. _this._generateHarmonics = true;
  83068. _this._onLoad = null;
  83069. _this._onError = null;
  83070. /**
  83071. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  83072. */
  83073. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  83074. _this._isBlocking = true;
  83075. _this._rotationY = 0;
  83076. /**
  83077. * Gets or sets the center of the bounding box associated with the cube texture
  83078. * It must define where the camera used to render the texture was set
  83079. */
  83080. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  83081. if (!url) {
  83082. return _this;
  83083. }
  83084. _this.name = url;
  83085. _this.url = url;
  83086. _this.hasAlpha = false;
  83087. _this.isCube = true;
  83088. _this._textureMatrix = BABYLON.Matrix.Identity();
  83089. _this._onLoad = onLoad;
  83090. _this._onError = onError;
  83091. _this.gammaSpace = gammaSpace;
  83092. _this._noMipmap = noMipmap;
  83093. _this._size = size;
  83094. _this._texture = _this._getFromCache(url, _this._noMipmap);
  83095. if (!_this._texture) {
  83096. if (!scene.useDelayedTextureLoading) {
  83097. _this.loadTexture();
  83098. }
  83099. else {
  83100. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  83101. }
  83102. }
  83103. return _this;
  83104. }
  83105. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  83106. /**
  83107. * Gets wether or not the texture is blocking during loading.
  83108. */
  83109. get: function () {
  83110. return this._isBlocking;
  83111. },
  83112. /**
  83113. * Sets wether or not the texture is blocking during loading.
  83114. */
  83115. set: function (value) {
  83116. this._isBlocking = value;
  83117. },
  83118. enumerable: true,
  83119. configurable: true
  83120. });
  83121. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  83122. /**
  83123. * Gets texture matrix rotation angle around Y axis radians.
  83124. */
  83125. get: function () {
  83126. return this._rotationY;
  83127. },
  83128. /**
  83129. * Sets texture matrix rotation angle around Y axis in radians.
  83130. */
  83131. set: function (value) {
  83132. this._rotationY = value;
  83133. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  83134. },
  83135. enumerable: true,
  83136. configurable: true
  83137. });
  83138. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  83139. get: function () {
  83140. return this._boundingBoxSize;
  83141. },
  83142. /**
  83143. * Gets or sets the size of the bounding box associated with the cube texture
  83144. * When defined, the cubemap will switch to local mode
  83145. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  83146. * @example https://www.babylonjs-playground.com/#RNASML
  83147. */
  83148. set: function (value) {
  83149. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  83150. return;
  83151. }
  83152. this._boundingBoxSize = value;
  83153. var scene = this.getScene();
  83154. if (scene) {
  83155. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  83156. }
  83157. },
  83158. enumerable: true,
  83159. configurable: true
  83160. });
  83161. /**
  83162. * Occurs when the file is raw .hdr file.
  83163. */
  83164. HDRCubeTexture.prototype.loadTexture = function () {
  83165. var _this = this;
  83166. var callback = function (buffer) {
  83167. _this.lodGenerationOffset = 0.0;
  83168. _this.lodGenerationScale = 0.8;
  83169. var scene = _this.getScene();
  83170. if (!scene) {
  83171. return null;
  83172. }
  83173. // Extract the raw linear data.
  83174. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  83175. // Generate harmonics if needed.
  83176. if (_this._generateHarmonics) {
  83177. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  83178. _this.sphericalPolynomial = sphericalPolynomial;
  83179. }
  83180. var results = [];
  83181. var byteArray = null;
  83182. // Push each faces.
  83183. for (var j = 0; j < 6; j++) {
  83184. // Create uintarray fallback.
  83185. if (!scene.getEngine().getCaps().textureFloat) {
  83186. // 3 channels of 1 bytes per pixel in bytes.
  83187. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  83188. byteArray = new Uint8Array(byteBuffer);
  83189. }
  83190. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  83191. // If special cases.
  83192. if (_this.gammaSpace || byteArray) {
  83193. for (var i = 0; i < _this._size * _this._size; i++) {
  83194. // Put in gamma space if requested.
  83195. if (_this.gammaSpace) {
  83196. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  83197. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  83198. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  83199. }
  83200. // Convert to int texture for fallback.
  83201. if (byteArray) {
  83202. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  83203. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  83204. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  83205. // May use luminance instead if the result is not accurate.
  83206. var max = Math.max(Math.max(r, g), b);
  83207. if (max > 255) {
  83208. var scale = 255 / max;
  83209. r *= scale;
  83210. g *= scale;
  83211. b *= scale;
  83212. }
  83213. byteArray[(i * 3) + 0] = r;
  83214. byteArray[(i * 3) + 1] = g;
  83215. byteArray[(i * 3) + 2] = b;
  83216. }
  83217. }
  83218. }
  83219. if (byteArray) {
  83220. results.push(byteArray);
  83221. }
  83222. else {
  83223. results.push(dataFace);
  83224. }
  83225. }
  83226. return results;
  83227. };
  83228. var scene = this.getScene();
  83229. if (scene) {
  83230. 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);
  83231. }
  83232. };
  83233. HDRCubeTexture.prototype.clone = function () {
  83234. var scene = this.getScene();
  83235. if (!scene) {
  83236. return this;
  83237. }
  83238. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  83239. // Base texture
  83240. newTexture.level = this.level;
  83241. newTexture.wrapU = this.wrapU;
  83242. newTexture.wrapV = this.wrapV;
  83243. newTexture.coordinatesIndex = this.coordinatesIndex;
  83244. newTexture.coordinatesMode = this.coordinatesMode;
  83245. return newTexture;
  83246. };
  83247. // Methods
  83248. HDRCubeTexture.prototype.delayLoad = function () {
  83249. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  83250. return;
  83251. }
  83252. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  83253. this._texture = this._getFromCache(this.url, this._noMipmap);
  83254. if (!this._texture) {
  83255. this.loadTexture();
  83256. }
  83257. };
  83258. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  83259. return this._textureMatrix;
  83260. };
  83261. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  83262. this._textureMatrix = value;
  83263. };
  83264. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  83265. var texture = null;
  83266. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  83267. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  83268. texture.name = parsedTexture.name;
  83269. texture.hasAlpha = parsedTexture.hasAlpha;
  83270. texture.level = parsedTexture.level;
  83271. texture.coordinatesMode = parsedTexture.coordinatesMode;
  83272. texture.isBlocking = parsedTexture.isBlocking;
  83273. }
  83274. if (texture) {
  83275. if (parsedTexture.boundingBoxPosition) {
  83276. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  83277. }
  83278. if (parsedTexture.boundingBoxSize) {
  83279. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  83280. }
  83281. if (parsedTexture.rotationY) {
  83282. texture.rotationY = parsedTexture.rotationY;
  83283. }
  83284. }
  83285. return texture;
  83286. };
  83287. HDRCubeTexture.prototype.serialize = function () {
  83288. if (!this.name) {
  83289. return null;
  83290. }
  83291. var serializationObject = {};
  83292. serializationObject.name = this.name;
  83293. serializationObject.hasAlpha = this.hasAlpha;
  83294. serializationObject.isCube = true;
  83295. serializationObject.level = this.level;
  83296. serializationObject.size = this._size;
  83297. serializationObject.coordinatesMode = this.coordinatesMode;
  83298. serializationObject.useInGammaSpace = this.gammaSpace;
  83299. serializationObject.generateHarmonics = this._generateHarmonics;
  83300. serializationObject.customType = "BABYLON.HDRCubeTexture";
  83301. serializationObject.noMipmap = this._noMipmap;
  83302. serializationObject.isBlocking = this._isBlocking;
  83303. serializationObject.rotationY = this._rotationY;
  83304. return serializationObject;
  83305. };
  83306. HDRCubeTexture._facesMapping = [
  83307. "right",
  83308. "left",
  83309. "up",
  83310. "down",
  83311. "front",
  83312. "back"
  83313. ];
  83314. return HDRCubeTexture;
  83315. }(BABYLON.BaseTexture));
  83316. BABYLON.HDRCubeTexture = HDRCubeTexture;
  83317. })(BABYLON || (BABYLON = {}));
  83318. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  83319. var BABYLON;
  83320. (function (BABYLON) {
  83321. var IndexedVector2 = /** @class */ (function (_super) {
  83322. __extends(IndexedVector2, _super);
  83323. function IndexedVector2(original, index) {
  83324. var _this = _super.call(this, original.x, original.y) || this;
  83325. _this.index = index;
  83326. return _this;
  83327. }
  83328. return IndexedVector2;
  83329. }(BABYLON.Vector2));
  83330. var PolygonPoints = /** @class */ (function () {
  83331. function PolygonPoints() {
  83332. this.elements = new Array();
  83333. }
  83334. PolygonPoints.prototype.add = function (originalPoints) {
  83335. var _this = this;
  83336. var result = new Array();
  83337. originalPoints.forEach(function (point) {
  83338. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  83339. var newPoint = new IndexedVector2(point, _this.elements.length);
  83340. result.push(newPoint);
  83341. _this.elements.push(newPoint);
  83342. }
  83343. });
  83344. return result;
  83345. };
  83346. PolygonPoints.prototype.computeBounds = function () {
  83347. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83348. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83349. this.elements.forEach(function (point) {
  83350. // x
  83351. if (point.x < lmin.x) {
  83352. lmin.x = point.x;
  83353. }
  83354. else if (point.x > lmax.x) {
  83355. lmax.x = point.x;
  83356. }
  83357. // y
  83358. if (point.y < lmin.y) {
  83359. lmin.y = point.y;
  83360. }
  83361. else if (point.y > lmax.y) {
  83362. lmax.y = point.y;
  83363. }
  83364. });
  83365. return {
  83366. min: lmin,
  83367. max: lmax,
  83368. width: lmax.x - lmin.x,
  83369. height: lmax.y - lmin.y
  83370. };
  83371. };
  83372. return PolygonPoints;
  83373. }());
  83374. var Polygon = /** @class */ (function () {
  83375. function Polygon() {
  83376. }
  83377. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  83378. return [
  83379. new BABYLON.Vector2(xmin, ymin),
  83380. new BABYLON.Vector2(xmax, ymin),
  83381. new BABYLON.Vector2(xmax, ymax),
  83382. new BABYLON.Vector2(xmin, ymax)
  83383. ];
  83384. };
  83385. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  83386. if (cx === void 0) { cx = 0; }
  83387. if (cy === void 0) { cy = 0; }
  83388. if (numberOfSides === void 0) { numberOfSides = 32; }
  83389. var result = new Array();
  83390. var angle = 0;
  83391. var increment = (Math.PI * 2) / numberOfSides;
  83392. for (var i = 0; i < numberOfSides; i++) {
  83393. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  83394. angle -= increment;
  83395. }
  83396. return result;
  83397. };
  83398. Polygon.Parse = function (input) {
  83399. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  83400. var i, result = [];
  83401. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  83402. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  83403. }
  83404. return result;
  83405. };
  83406. Polygon.StartingAt = function (x, y) {
  83407. return BABYLON.Path2.StartingAt(x, y);
  83408. };
  83409. return Polygon;
  83410. }());
  83411. BABYLON.Polygon = Polygon;
  83412. var PolygonMeshBuilder = /** @class */ (function () {
  83413. function PolygonMeshBuilder(name, contours, scene) {
  83414. this._points = new PolygonPoints();
  83415. this._outlinepoints = new PolygonPoints();
  83416. this._holes = new Array();
  83417. this._epoints = new Array();
  83418. this._eholes = new Array();
  83419. this._name = name;
  83420. this._scene = scene;
  83421. var points;
  83422. if (contours instanceof BABYLON.Path2) {
  83423. points = contours.getPoints();
  83424. }
  83425. else {
  83426. points = contours;
  83427. }
  83428. this._addToepoint(points);
  83429. this._points.add(points);
  83430. this._outlinepoints.add(points);
  83431. if (typeof earcut === 'undefined') {
  83432. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  83433. }
  83434. }
  83435. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  83436. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  83437. var p = points_1[_i];
  83438. this._epoints.push(p.x, p.y);
  83439. }
  83440. };
  83441. PolygonMeshBuilder.prototype.addHole = function (hole) {
  83442. this._points.add(hole);
  83443. var holepoints = new PolygonPoints();
  83444. holepoints.add(hole);
  83445. this._holes.push(holepoints);
  83446. this._eholes.push(this._epoints.length / 2);
  83447. this._addToepoint(hole);
  83448. return this;
  83449. };
  83450. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  83451. var _this = this;
  83452. if (updatable === void 0) { updatable = false; }
  83453. if (depth === void 0) { depth = 0; }
  83454. var result = new BABYLON.Mesh(this._name, this._scene);
  83455. var normals = new Array();
  83456. var positions = new Array();
  83457. var uvs = new Array();
  83458. var bounds = this._points.computeBounds();
  83459. this._points.elements.forEach(function (p) {
  83460. normals.push(0, 1.0, 0);
  83461. positions.push(p.x, 0, p.y);
  83462. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  83463. });
  83464. var indices = new Array();
  83465. var res = earcut(this._epoints, this._eholes, 2);
  83466. for (var i = 0; i < res.length; i++) {
  83467. indices.push(res[i]);
  83468. }
  83469. if (depth > 0) {
  83470. var positionscount = (positions.length / 3); //get the current pointcount
  83471. this._points.elements.forEach(function (p) {
  83472. normals.push(0, -1.0, 0);
  83473. positions.push(p.x, -depth, p.y);
  83474. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  83475. });
  83476. var totalCount = indices.length;
  83477. for (var i = 0; i < totalCount; i += 3) {
  83478. var i0 = indices[i + 0];
  83479. var i1 = indices[i + 1];
  83480. var i2 = indices[i + 2];
  83481. indices.push(i2 + positionscount);
  83482. indices.push(i1 + positionscount);
  83483. indices.push(i0 + positionscount);
  83484. }
  83485. //Add the sides
  83486. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  83487. this._holes.forEach(function (hole) {
  83488. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  83489. });
  83490. }
  83491. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  83492. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  83493. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  83494. result.setIndices(indices);
  83495. return result;
  83496. };
  83497. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  83498. var StartIndex = positions.length / 3;
  83499. var ulength = 0;
  83500. for (var i = 0; i < points.elements.length; i++) {
  83501. var p = points.elements[i];
  83502. var p1;
  83503. if ((i + 1) > points.elements.length - 1) {
  83504. p1 = points.elements[0];
  83505. }
  83506. else {
  83507. p1 = points.elements[i + 1];
  83508. }
  83509. positions.push(p.x, 0, p.y);
  83510. positions.push(p.x, -depth, p.y);
  83511. positions.push(p1.x, 0, p1.y);
  83512. positions.push(p1.x, -depth, p1.y);
  83513. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  83514. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  83515. var v3 = v2.subtract(v1);
  83516. var v4 = new BABYLON.Vector3(0, 1, 0);
  83517. var vn = BABYLON.Vector3.Cross(v3, v4);
  83518. vn = vn.normalize();
  83519. uvs.push(ulength / bounds.width, 0);
  83520. uvs.push(ulength / bounds.width, 1);
  83521. ulength += v3.length();
  83522. uvs.push((ulength / bounds.width), 0);
  83523. uvs.push((ulength / bounds.width), 1);
  83524. if (!flip) {
  83525. normals.push(-vn.x, -vn.y, -vn.z);
  83526. normals.push(-vn.x, -vn.y, -vn.z);
  83527. normals.push(-vn.x, -vn.y, -vn.z);
  83528. normals.push(-vn.x, -vn.y, -vn.z);
  83529. indices.push(StartIndex);
  83530. indices.push(StartIndex + 1);
  83531. indices.push(StartIndex + 2);
  83532. indices.push(StartIndex + 1);
  83533. indices.push(StartIndex + 3);
  83534. indices.push(StartIndex + 2);
  83535. }
  83536. else {
  83537. normals.push(vn.x, vn.y, vn.z);
  83538. normals.push(vn.x, vn.y, vn.z);
  83539. normals.push(vn.x, vn.y, vn.z);
  83540. normals.push(vn.x, vn.y, vn.z);
  83541. indices.push(StartIndex);
  83542. indices.push(StartIndex + 2);
  83543. indices.push(StartIndex + 1);
  83544. indices.push(StartIndex + 1);
  83545. indices.push(StartIndex + 2);
  83546. indices.push(StartIndex + 3);
  83547. }
  83548. StartIndex += 4;
  83549. }
  83550. ;
  83551. };
  83552. return PolygonMeshBuilder;
  83553. }());
  83554. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83555. })(BABYLON || (BABYLON = {}));
  83556. //# sourceMappingURL=babylon.polygonMesh.js.map
  83557. var BABYLON;
  83558. (function (BABYLON) {
  83559. // Unique ID when we import meshes from Babylon to CSG
  83560. var currentCSGMeshId = 0;
  83561. // # class Vertex
  83562. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83563. // one to provide additional features like texture coordinates and vertex
  83564. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83565. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83566. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83567. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83568. // is not used anywhere else.
  83569. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83570. var Vertex = /** @class */ (function () {
  83571. function Vertex(pos, normal, uv) {
  83572. this.pos = pos;
  83573. this.normal = normal;
  83574. this.uv = uv;
  83575. }
  83576. Vertex.prototype.clone = function () {
  83577. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83578. };
  83579. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83580. // orientation of a polygon is flipped.
  83581. Vertex.prototype.flip = function () {
  83582. this.normal = this.normal.scale(-1);
  83583. };
  83584. // Create a new vertex between this vertex and `other` by linearly
  83585. // interpolating all properties using a parameter of `t`. Subclasses should
  83586. // override this to interpolate additional properties.
  83587. Vertex.prototype.interpolate = function (other, t) {
  83588. 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));
  83589. };
  83590. return Vertex;
  83591. }());
  83592. // # class Plane
  83593. // Represents a plane in 3D space.
  83594. var Plane = /** @class */ (function () {
  83595. function Plane(normal, w) {
  83596. this.normal = normal;
  83597. this.w = w;
  83598. }
  83599. Plane.FromPoints = function (a, b, c) {
  83600. var v0 = c.subtract(a);
  83601. var v1 = b.subtract(a);
  83602. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83603. return null;
  83604. }
  83605. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83606. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83607. };
  83608. Plane.prototype.clone = function () {
  83609. return new Plane(this.normal.clone(), this.w);
  83610. };
  83611. Plane.prototype.flip = function () {
  83612. this.normal.scaleInPlace(-1);
  83613. this.w = -this.w;
  83614. };
  83615. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83616. // fragments in the appropriate lists. Coplanar polygons go into either
  83617. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83618. // respect to this plane. Polygons in front or in back of this plane go into
  83619. // either `front` or `back`.
  83620. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83621. var COPLANAR = 0;
  83622. var FRONT = 1;
  83623. var BACK = 2;
  83624. var SPANNING = 3;
  83625. // Classify each point as well as the entire polygon into one of the above
  83626. // four classes.
  83627. var polygonType = 0;
  83628. var types = [];
  83629. var i;
  83630. var t;
  83631. for (i = 0; i < polygon.vertices.length; i++) {
  83632. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83633. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83634. polygonType |= type;
  83635. types.push(type);
  83636. }
  83637. // Put the polygon in the correct list, splitting it when necessary.
  83638. switch (polygonType) {
  83639. case COPLANAR:
  83640. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83641. break;
  83642. case FRONT:
  83643. front.push(polygon);
  83644. break;
  83645. case BACK:
  83646. back.push(polygon);
  83647. break;
  83648. case SPANNING:
  83649. var f = [], b = [];
  83650. for (i = 0; i < polygon.vertices.length; i++) {
  83651. var j = (i + 1) % polygon.vertices.length;
  83652. var ti = types[i], tj = types[j];
  83653. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83654. if (ti !== BACK)
  83655. f.push(vi);
  83656. if (ti !== FRONT)
  83657. b.push(ti !== BACK ? vi.clone() : vi);
  83658. if ((ti | tj) === SPANNING) {
  83659. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83660. var v = vi.interpolate(vj, t);
  83661. f.push(v);
  83662. b.push(v.clone());
  83663. }
  83664. }
  83665. var poly;
  83666. if (f.length >= 3) {
  83667. poly = new Polygon(f, polygon.shared);
  83668. if (poly.plane)
  83669. front.push(poly);
  83670. }
  83671. if (b.length >= 3) {
  83672. poly = new Polygon(b, polygon.shared);
  83673. if (poly.plane)
  83674. back.push(poly);
  83675. }
  83676. break;
  83677. }
  83678. };
  83679. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83680. // point is on the plane.
  83681. Plane.EPSILON = 1e-5;
  83682. return Plane;
  83683. }());
  83684. // # class Polygon
  83685. // Represents a convex polygon. The vertices used to initialize a polygon must
  83686. // be coplanar and form a convex loop.
  83687. //
  83688. // Each convex polygon has a `shared` property, which is shared between all
  83689. // polygons that are clones of each other or were split from the same polygon.
  83690. // This can be used to define per-polygon properties (such as surface color).
  83691. var Polygon = /** @class */ (function () {
  83692. function Polygon(vertices, shared) {
  83693. this.vertices = vertices;
  83694. this.shared = shared;
  83695. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83696. }
  83697. Polygon.prototype.clone = function () {
  83698. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83699. return new Polygon(vertices, this.shared);
  83700. };
  83701. Polygon.prototype.flip = function () {
  83702. this.vertices.reverse().map(function (v) { v.flip(); });
  83703. this.plane.flip();
  83704. };
  83705. return Polygon;
  83706. }());
  83707. // # class Node
  83708. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83709. // by picking a polygon to split along. That polygon (and all other coplanar
  83710. // polygons) are added directly to that node and the other polygons are added to
  83711. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83712. // no distinction between internal and leaf nodes.
  83713. var Node = /** @class */ (function () {
  83714. function Node(polygons) {
  83715. this.plane = null;
  83716. this.front = null;
  83717. this.back = null;
  83718. this.polygons = new Array();
  83719. if (polygons) {
  83720. this.build(polygons);
  83721. }
  83722. }
  83723. Node.prototype.clone = function () {
  83724. var node = new Node();
  83725. node.plane = this.plane && this.plane.clone();
  83726. node.front = this.front && this.front.clone();
  83727. node.back = this.back && this.back.clone();
  83728. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  83729. return node;
  83730. };
  83731. // Convert solid space to empty space and empty space to solid space.
  83732. Node.prototype.invert = function () {
  83733. for (var i = 0; i < this.polygons.length; i++) {
  83734. this.polygons[i].flip();
  83735. }
  83736. if (this.plane) {
  83737. this.plane.flip();
  83738. }
  83739. if (this.front) {
  83740. this.front.invert();
  83741. }
  83742. if (this.back) {
  83743. this.back.invert();
  83744. }
  83745. var temp = this.front;
  83746. this.front = this.back;
  83747. this.back = temp;
  83748. };
  83749. // Recursively remove all polygons in `polygons` that are inside this BSP
  83750. // tree.
  83751. Node.prototype.clipPolygons = function (polygons) {
  83752. if (!this.plane)
  83753. return polygons.slice();
  83754. var front = new Array(), back = new Array();
  83755. for (var i = 0; i < polygons.length; i++) {
  83756. this.plane.splitPolygon(polygons[i], front, back, front, back);
  83757. }
  83758. if (this.front) {
  83759. front = this.front.clipPolygons(front);
  83760. }
  83761. if (this.back) {
  83762. back = this.back.clipPolygons(back);
  83763. }
  83764. else {
  83765. back = [];
  83766. }
  83767. return front.concat(back);
  83768. };
  83769. // Remove all polygons in this BSP tree that are inside the other BSP tree
  83770. // `bsp`.
  83771. Node.prototype.clipTo = function (bsp) {
  83772. this.polygons = bsp.clipPolygons(this.polygons);
  83773. if (this.front)
  83774. this.front.clipTo(bsp);
  83775. if (this.back)
  83776. this.back.clipTo(bsp);
  83777. };
  83778. // Return a list of all polygons in this BSP tree.
  83779. Node.prototype.allPolygons = function () {
  83780. var polygons = this.polygons.slice();
  83781. if (this.front)
  83782. polygons = polygons.concat(this.front.allPolygons());
  83783. if (this.back)
  83784. polygons = polygons.concat(this.back.allPolygons());
  83785. return polygons;
  83786. };
  83787. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  83788. // new polygons are filtered down to the bottom of the tree and become new
  83789. // nodes there. Each set of polygons is partitioned using the first polygon
  83790. // (no heuristic is used to pick a good split).
  83791. Node.prototype.build = function (polygons) {
  83792. if (!polygons.length)
  83793. return;
  83794. if (!this.plane)
  83795. this.plane = polygons[0].plane.clone();
  83796. var front = new Array(), back = new Array();
  83797. for (var i = 0; i < polygons.length; i++) {
  83798. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  83799. }
  83800. if (front.length) {
  83801. if (!this.front)
  83802. this.front = new Node();
  83803. this.front.build(front);
  83804. }
  83805. if (back.length) {
  83806. if (!this.back)
  83807. this.back = new Node();
  83808. this.back.build(back);
  83809. }
  83810. };
  83811. return Node;
  83812. }());
  83813. var CSG = /** @class */ (function () {
  83814. function CSG() {
  83815. this.polygons = new Array();
  83816. }
  83817. // Convert BABYLON.Mesh to BABYLON.CSG
  83818. CSG.FromMesh = function (mesh) {
  83819. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  83820. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  83821. if (mesh instanceof BABYLON.Mesh) {
  83822. mesh.computeWorldMatrix(true);
  83823. matrix = mesh.getWorldMatrix();
  83824. meshPosition = mesh.position.clone();
  83825. meshRotation = mesh.rotation.clone();
  83826. if (mesh.rotationQuaternion) {
  83827. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  83828. }
  83829. meshScaling = mesh.scaling.clone();
  83830. }
  83831. else {
  83832. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  83833. }
  83834. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83835. var subMeshes = mesh.subMeshes;
  83836. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  83837. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  83838. vertices = [];
  83839. for (var j = 0; j < 3; j++) {
  83840. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  83841. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  83842. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  83843. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  83844. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  83845. vertex = new Vertex(position, normal, uv);
  83846. vertices.push(vertex);
  83847. }
  83848. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  83849. // To handle the case of degenerated triangle
  83850. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  83851. if (polygon.plane)
  83852. polygons.push(polygon);
  83853. }
  83854. }
  83855. var csg = CSG.FromPolygons(polygons);
  83856. csg.matrix = matrix;
  83857. csg.position = meshPosition;
  83858. csg.rotation = meshRotation;
  83859. csg.scaling = meshScaling;
  83860. csg.rotationQuaternion = meshRotationQuaternion;
  83861. currentCSGMeshId++;
  83862. return csg;
  83863. };
  83864. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  83865. CSG.FromPolygons = function (polygons) {
  83866. var csg = new CSG();
  83867. csg.polygons = polygons;
  83868. return csg;
  83869. };
  83870. CSG.prototype.clone = function () {
  83871. var csg = new CSG();
  83872. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  83873. csg.copyTransformAttributes(this);
  83874. return csg;
  83875. };
  83876. CSG.prototype.union = function (csg) {
  83877. var a = new Node(this.clone().polygons);
  83878. var b = new Node(csg.clone().polygons);
  83879. a.clipTo(b);
  83880. b.clipTo(a);
  83881. b.invert();
  83882. b.clipTo(a);
  83883. b.invert();
  83884. a.build(b.allPolygons());
  83885. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83886. };
  83887. CSG.prototype.unionInPlace = function (csg) {
  83888. var a = new Node(this.polygons);
  83889. var b = new Node(csg.polygons);
  83890. a.clipTo(b);
  83891. b.clipTo(a);
  83892. b.invert();
  83893. b.clipTo(a);
  83894. b.invert();
  83895. a.build(b.allPolygons());
  83896. this.polygons = a.allPolygons();
  83897. };
  83898. CSG.prototype.subtract = function (csg) {
  83899. var a = new Node(this.clone().polygons);
  83900. var b = new Node(csg.clone().polygons);
  83901. a.invert();
  83902. a.clipTo(b);
  83903. b.clipTo(a);
  83904. b.invert();
  83905. b.clipTo(a);
  83906. b.invert();
  83907. a.build(b.allPolygons());
  83908. a.invert();
  83909. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83910. };
  83911. CSG.prototype.subtractInPlace = function (csg) {
  83912. var a = new Node(this.polygons);
  83913. var b = new Node(csg.polygons);
  83914. a.invert();
  83915. a.clipTo(b);
  83916. b.clipTo(a);
  83917. b.invert();
  83918. b.clipTo(a);
  83919. b.invert();
  83920. a.build(b.allPolygons());
  83921. a.invert();
  83922. this.polygons = a.allPolygons();
  83923. };
  83924. CSG.prototype.intersect = function (csg) {
  83925. var a = new Node(this.clone().polygons);
  83926. var b = new Node(csg.clone().polygons);
  83927. a.invert();
  83928. b.clipTo(a);
  83929. b.invert();
  83930. a.clipTo(b);
  83931. b.clipTo(a);
  83932. a.build(b.allPolygons());
  83933. a.invert();
  83934. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83935. };
  83936. CSG.prototype.intersectInPlace = function (csg) {
  83937. var a = new Node(this.polygons);
  83938. var b = new Node(csg.polygons);
  83939. a.invert();
  83940. b.clipTo(a);
  83941. b.invert();
  83942. a.clipTo(b);
  83943. b.clipTo(a);
  83944. a.build(b.allPolygons());
  83945. a.invert();
  83946. this.polygons = a.allPolygons();
  83947. };
  83948. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  83949. // not modified.
  83950. CSG.prototype.inverse = function () {
  83951. var csg = this.clone();
  83952. csg.inverseInPlace();
  83953. return csg;
  83954. };
  83955. CSG.prototype.inverseInPlace = function () {
  83956. this.polygons.map(function (p) { p.flip(); });
  83957. };
  83958. // This is used to keep meshes transformations so they can be restored
  83959. // when we build back a Babylon Mesh
  83960. // NB : All CSG operations are performed in world coordinates
  83961. CSG.prototype.copyTransformAttributes = function (csg) {
  83962. this.matrix = csg.matrix;
  83963. this.position = csg.position;
  83964. this.rotation = csg.rotation;
  83965. this.scaling = csg.scaling;
  83966. this.rotationQuaternion = csg.rotationQuaternion;
  83967. return this;
  83968. };
  83969. // Build Raw mesh from CSG
  83970. // Coordinates here are in world space
  83971. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  83972. var matrix = this.matrix.clone();
  83973. matrix.invert();
  83974. 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;
  83975. if (keepSubMeshes) {
  83976. // Sort Polygons, since subMeshes are indices range
  83977. polygons.sort(function (a, b) {
  83978. if (a.shared.meshId === b.shared.meshId) {
  83979. return a.shared.subMeshId - b.shared.subMeshId;
  83980. }
  83981. else {
  83982. return a.shared.meshId - b.shared.meshId;
  83983. }
  83984. });
  83985. }
  83986. for (var i = 0, il = polygons.length; i < il; i++) {
  83987. polygon = polygons[i];
  83988. // Building SubMeshes
  83989. if (!subMesh_dict[polygon.shared.meshId]) {
  83990. subMesh_dict[polygon.shared.meshId] = {};
  83991. }
  83992. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  83993. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  83994. indexStart: +Infinity,
  83995. indexEnd: -Infinity,
  83996. materialIndex: polygon.shared.materialIndex
  83997. };
  83998. }
  83999. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  84000. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  84001. polygonIndices[0] = 0;
  84002. polygonIndices[1] = j - 1;
  84003. polygonIndices[2] = j;
  84004. for (var k = 0; k < 3; k++) {
  84005. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  84006. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  84007. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  84008. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  84009. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  84010. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  84011. // Check if 2 points can be merged
  84012. if (!(typeof vertex_idx !== 'undefined' &&
  84013. normals[vertex_idx * 3] === localNormal.x &&
  84014. normals[vertex_idx * 3 + 1] === localNormal.y &&
  84015. normals[vertex_idx * 3 + 2] === localNormal.z &&
  84016. uvs[vertex_idx * 2] === uv.x &&
  84017. uvs[vertex_idx * 2 + 1] === uv.y)) {
  84018. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  84019. uvs.push(uv.x, uv.y);
  84020. normals.push(normal.x, normal.y, normal.z);
  84021. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  84022. }
  84023. indices.push(vertex_idx);
  84024. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  84025. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  84026. currentIndex++;
  84027. }
  84028. }
  84029. }
  84030. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  84031. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  84032. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  84033. mesh.setIndices(indices, null);
  84034. if (keepSubMeshes) {
  84035. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  84036. var materialIndexOffset = 0, materialMaxIndex;
  84037. mesh.subMeshes = new Array();
  84038. for (var m in subMesh_dict) {
  84039. materialMaxIndex = -1;
  84040. for (var sm in subMesh_dict[m]) {
  84041. subMesh_obj = subMesh_dict[m][sm];
  84042. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  84043. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  84044. }
  84045. materialIndexOffset += ++materialMaxIndex;
  84046. }
  84047. }
  84048. return mesh;
  84049. };
  84050. // Build Mesh from CSG taking material and transforms into account
  84051. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  84052. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  84053. mesh.material = material;
  84054. mesh.position.copyFrom(this.position);
  84055. mesh.rotation.copyFrom(this.rotation);
  84056. if (this.rotationQuaternion) {
  84057. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  84058. }
  84059. mesh.scaling.copyFrom(this.scaling);
  84060. mesh.computeWorldMatrix(true);
  84061. return mesh;
  84062. };
  84063. return CSG;
  84064. }());
  84065. BABYLON.CSG = CSG;
  84066. })(BABYLON || (BABYLON = {}));
  84067. //# sourceMappingURL=babylon.csg.js.map
  84068. var BABYLON;
  84069. (function (BABYLON) {
  84070. var LensFlare = /** @class */ (function () {
  84071. function LensFlare(size, position, color, imgUrl, system) {
  84072. this.size = size;
  84073. this.position = position;
  84074. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  84075. this.color = color || new BABYLON.Color3(1, 1, 1);
  84076. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  84077. this._system = system;
  84078. system.lensFlares.push(this);
  84079. }
  84080. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  84081. return new LensFlare(size, position, color, imgUrl, system);
  84082. };
  84083. LensFlare.prototype.dispose = function () {
  84084. if (this.texture) {
  84085. this.texture.dispose();
  84086. }
  84087. // Remove from scene
  84088. var index = this._system.lensFlares.indexOf(this);
  84089. this._system.lensFlares.splice(index, 1);
  84090. };
  84091. ;
  84092. return LensFlare;
  84093. }());
  84094. BABYLON.LensFlare = LensFlare;
  84095. })(BABYLON || (BABYLON = {}));
  84096. //# sourceMappingURL=babylon.lensFlare.js.map
  84097. var BABYLON;
  84098. (function (BABYLON) {
  84099. // Adds the parser to the scene parsers.
  84100. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  84101. // Lens flares
  84102. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  84103. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  84104. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  84105. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  84106. container.lensFlareSystems.push(lf);
  84107. }
  84108. }
  84109. });
  84110. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  84111. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84112. if (this.lensFlareSystems[index].name === name) {
  84113. return this.lensFlareSystems[index];
  84114. }
  84115. }
  84116. return null;
  84117. };
  84118. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  84119. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84120. if (this.lensFlareSystems[index].id === id) {
  84121. return this.lensFlareSystems[index];
  84122. }
  84123. }
  84124. return null;
  84125. };
  84126. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  84127. var index = this.lensFlareSystems.indexOf(toRemove);
  84128. if (index !== -1) {
  84129. this.lensFlareSystems.splice(index, 1);
  84130. }
  84131. return index;
  84132. };
  84133. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  84134. this.lensFlareSystems.push(newLensFlareSystem);
  84135. };
  84136. /**
  84137. * Defines the lens flare scene component responsible to manage any lens flares
  84138. * in a given scene.
  84139. */
  84140. var LensFlareSystemSceneComponent = /** @class */ (function () {
  84141. /**
  84142. * Creates a new instance of the component for the given scene
  84143. * @param scene Defines the scene to register the component in
  84144. */
  84145. function LensFlareSystemSceneComponent(scene) {
  84146. /**
  84147. * The component name helpfull to identify the component in the list of scene components.
  84148. */
  84149. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  84150. this.scene = scene;
  84151. scene.lensFlareSystems = new Array();
  84152. }
  84153. /**
  84154. * Registers the component in a given scene
  84155. */
  84156. LensFlareSystemSceneComponent.prototype.register = function () {
  84157. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  84158. };
  84159. /**
  84160. * Rebuilds the elements related to this component in case of
  84161. * context lost for instance.
  84162. */
  84163. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  84164. // Nothing to do for lens flare
  84165. };
  84166. /**
  84167. * Adds all the element from the container to the scene
  84168. * @param container the container holding the elements
  84169. */
  84170. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  84171. var _this = this;
  84172. if (!container.lensFlareSystems) {
  84173. return;
  84174. }
  84175. container.lensFlareSystems.forEach(function (o) {
  84176. _this.scene.addLensFlareSystem(o);
  84177. });
  84178. };
  84179. /**
  84180. * Removes all the elements in the container from the scene
  84181. * @param container contains the elements to remove
  84182. */
  84183. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  84184. var _this = this;
  84185. if (!container.lensFlareSystems) {
  84186. return;
  84187. }
  84188. container.lensFlareSystems.forEach(function (o) {
  84189. _this.scene.removeLensFlareSystem(o);
  84190. });
  84191. };
  84192. /**
  84193. * Serializes the component data to the specified json object
  84194. * @param serializationObject The object to serialize to
  84195. */
  84196. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  84197. // Lens flares
  84198. serializationObject.lensFlareSystems = [];
  84199. var lensFlareSystems = this.scene.lensFlareSystems;
  84200. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  84201. var lensFlareSystem = lensFlareSystems_1[_i];
  84202. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  84203. }
  84204. };
  84205. /**
  84206. * Disposes the component and the associated ressources.
  84207. */
  84208. LensFlareSystemSceneComponent.prototype.dispose = function () {
  84209. var lensFlareSystems = this.scene.lensFlareSystems;
  84210. while (lensFlareSystems.length) {
  84211. lensFlareSystems[0].dispose();
  84212. }
  84213. };
  84214. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  84215. // Lens flares
  84216. if (this.scene.lensFlaresEnabled) {
  84217. var lensFlareSystems = this.scene.lensFlareSystems;
  84218. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84219. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  84220. var lensFlareSystem = lensFlareSystems_2[_i];
  84221. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  84222. lensFlareSystem.render();
  84223. }
  84224. }
  84225. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84226. }
  84227. };
  84228. return LensFlareSystemSceneComponent;
  84229. }());
  84230. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  84231. })(BABYLON || (BABYLON = {}));
  84232. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  84233. var BABYLON;
  84234. (function (BABYLON) {
  84235. var LensFlareSystem = /** @class */ (function () {
  84236. function LensFlareSystem(name, emitter, scene) {
  84237. this.name = name;
  84238. this.lensFlares = new Array();
  84239. this.borderLimit = 300;
  84240. this.viewportBorder = 0;
  84241. this.layerMask = 0x0FFFFFFF;
  84242. this._vertexBuffers = {};
  84243. this._isEnabled = true;
  84244. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84245. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  84246. if (!component) {
  84247. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  84248. scene._addComponent(component);
  84249. }
  84250. this._emitter = emitter;
  84251. this.id = name;
  84252. scene.lensFlareSystems.push(this);
  84253. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  84254. var engine = scene.getEngine();
  84255. // VBO
  84256. var vertices = [];
  84257. vertices.push(1, 1);
  84258. vertices.push(-1, 1);
  84259. vertices.push(-1, -1);
  84260. vertices.push(1, -1);
  84261. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84262. // Indices
  84263. var indices = [];
  84264. indices.push(0);
  84265. indices.push(1);
  84266. indices.push(2);
  84267. indices.push(0);
  84268. indices.push(2);
  84269. indices.push(3);
  84270. this._indexBuffer = engine.createIndexBuffer(indices);
  84271. // Effects
  84272. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  84273. }
  84274. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  84275. get: function () {
  84276. return this._isEnabled;
  84277. },
  84278. set: function (value) {
  84279. this._isEnabled = value;
  84280. },
  84281. enumerable: true,
  84282. configurable: true
  84283. });
  84284. LensFlareSystem.prototype.getScene = function () {
  84285. return this._scene;
  84286. };
  84287. LensFlareSystem.prototype.getEmitter = function () {
  84288. return this._emitter;
  84289. };
  84290. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  84291. this._emitter = newEmitter;
  84292. };
  84293. LensFlareSystem.prototype.getEmitterPosition = function () {
  84294. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  84295. };
  84296. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  84297. var position = this.getEmitterPosition();
  84298. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  84299. this._positionX = position.x;
  84300. this._positionY = position.y;
  84301. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  84302. if (this.viewportBorder > 0) {
  84303. globalViewport.x -= this.viewportBorder;
  84304. globalViewport.y -= this.viewportBorder;
  84305. globalViewport.width += this.viewportBorder * 2;
  84306. globalViewport.height += this.viewportBorder * 2;
  84307. position.x += this.viewportBorder;
  84308. position.y += this.viewportBorder;
  84309. this._positionX += this.viewportBorder;
  84310. this._positionY += this.viewportBorder;
  84311. }
  84312. if (position.z > 0) {
  84313. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  84314. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  84315. return true;
  84316. }
  84317. return true;
  84318. }
  84319. return false;
  84320. };
  84321. LensFlareSystem.prototype._isVisible = function () {
  84322. if (!this._isEnabled || !this._scene.activeCamera) {
  84323. return false;
  84324. }
  84325. var emitterPosition = this.getEmitterPosition();
  84326. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  84327. var distance = direction.length();
  84328. direction.normalize();
  84329. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  84330. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  84331. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  84332. };
  84333. LensFlareSystem.prototype.render = function () {
  84334. if (!this._effect.isReady() || !this._scene.activeCamera)
  84335. return false;
  84336. var engine = this._scene.getEngine();
  84337. var viewport = this._scene.activeCamera.viewport;
  84338. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  84339. // Position
  84340. if (!this.computeEffectivePosition(globalViewport)) {
  84341. return false;
  84342. }
  84343. // Visibility
  84344. if (!this._isVisible()) {
  84345. return false;
  84346. }
  84347. // Intensity
  84348. var awayX;
  84349. var awayY;
  84350. if (this._positionX < this.borderLimit + globalViewport.x) {
  84351. awayX = this.borderLimit + globalViewport.x - this._positionX;
  84352. }
  84353. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  84354. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  84355. }
  84356. else {
  84357. awayX = 0;
  84358. }
  84359. if (this._positionY < this.borderLimit + globalViewport.y) {
  84360. awayY = this.borderLimit + globalViewport.y - this._positionY;
  84361. }
  84362. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  84363. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  84364. }
  84365. else {
  84366. awayY = 0;
  84367. }
  84368. var away = (awayX > awayY) ? awayX : awayY;
  84369. away -= this.viewportBorder;
  84370. if (away > this.borderLimit) {
  84371. away = this.borderLimit;
  84372. }
  84373. var intensity = 1.0 - (away / this.borderLimit);
  84374. if (intensity < 0) {
  84375. return false;
  84376. }
  84377. if (intensity > 1.0) {
  84378. intensity = 1.0;
  84379. }
  84380. if (this.viewportBorder > 0) {
  84381. globalViewport.x += this.viewportBorder;
  84382. globalViewport.y += this.viewportBorder;
  84383. globalViewport.width -= this.viewportBorder * 2;
  84384. globalViewport.height -= this.viewportBorder * 2;
  84385. this._positionX -= this.viewportBorder;
  84386. this._positionY -= this.viewportBorder;
  84387. }
  84388. // Position
  84389. var centerX = globalViewport.x + globalViewport.width / 2;
  84390. var centerY = globalViewport.y + globalViewport.height / 2;
  84391. var distX = centerX - this._positionX;
  84392. var distY = centerY - this._positionY;
  84393. // Effects
  84394. engine.enableEffect(this._effect);
  84395. engine.setState(false);
  84396. engine.setDepthBuffer(false);
  84397. // VBOs
  84398. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  84399. // Flares
  84400. for (var index = 0; index < this.lensFlares.length; index++) {
  84401. var flare = this.lensFlares[index];
  84402. engine.setAlphaMode(flare.alphaMode);
  84403. var x = centerX - (distX * flare.position);
  84404. var y = centerY - (distY * flare.position);
  84405. var cw = flare.size;
  84406. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  84407. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  84408. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  84409. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  84410. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  84411. // Texture
  84412. this._effect.setTexture("textureSampler", flare.texture);
  84413. // Color
  84414. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  84415. // Draw order
  84416. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84417. }
  84418. engine.setDepthBuffer(true);
  84419. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84420. return true;
  84421. };
  84422. LensFlareSystem.prototype.dispose = function () {
  84423. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84424. if (vertexBuffer) {
  84425. vertexBuffer.dispose();
  84426. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84427. }
  84428. if (this._indexBuffer) {
  84429. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84430. this._indexBuffer = null;
  84431. }
  84432. while (this.lensFlares.length) {
  84433. this.lensFlares[0].dispose();
  84434. }
  84435. // Remove from scene
  84436. var index = this._scene.lensFlareSystems.indexOf(this);
  84437. this._scene.lensFlareSystems.splice(index, 1);
  84438. };
  84439. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  84440. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  84441. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  84442. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  84443. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  84444. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  84445. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  84446. var parsedFlare = parsedLensFlareSystem.flares[index];
  84447. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  84448. }
  84449. return lensFlareSystem;
  84450. };
  84451. LensFlareSystem.prototype.serialize = function () {
  84452. var serializationObject = {};
  84453. serializationObject.id = this.id;
  84454. serializationObject.name = this.name;
  84455. serializationObject.emitterId = this.getEmitter().id;
  84456. serializationObject.borderLimit = this.borderLimit;
  84457. serializationObject.flares = [];
  84458. for (var index = 0; index < this.lensFlares.length; index++) {
  84459. var flare = this.lensFlares[index];
  84460. serializationObject.flares.push({
  84461. size: flare.size,
  84462. position: flare.position,
  84463. color: flare.color.asArray(),
  84464. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  84465. });
  84466. }
  84467. return serializationObject;
  84468. };
  84469. return LensFlareSystem;
  84470. }());
  84471. BABYLON.LensFlareSystem = LensFlareSystem;
  84472. })(BABYLON || (BABYLON = {}));
  84473. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  84474. var BABYLON;
  84475. (function (BABYLON) {
  84476. /**
  84477. * This is a holder class for the physics joint created by the physics plugin.
  84478. * It holds a set of functions to control the underlying joint.
  84479. */
  84480. var PhysicsJoint = /** @class */ (function () {
  84481. function PhysicsJoint(type, jointData) {
  84482. this.type = type;
  84483. this.jointData = jointData;
  84484. jointData.nativeParams = jointData.nativeParams || {};
  84485. }
  84486. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  84487. get: function () {
  84488. return this._physicsJoint;
  84489. },
  84490. set: function (newJoint) {
  84491. if (this._physicsJoint) {
  84492. //remove from the wolrd
  84493. }
  84494. this._physicsJoint = newJoint;
  84495. },
  84496. enumerable: true,
  84497. configurable: true
  84498. });
  84499. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  84500. set: function (physicsPlugin) {
  84501. this._physicsPlugin = physicsPlugin;
  84502. },
  84503. enumerable: true,
  84504. configurable: true
  84505. });
  84506. /**
  84507. * Execute a function that is physics-plugin specific.
  84508. * @param {Function} func the function that will be executed.
  84509. * It accepts two parameters: the physics world and the physics joint.
  84510. */
  84511. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  84512. func(this._physicsPlugin.world, this._physicsJoint);
  84513. };
  84514. //TODO check if the native joints are the same
  84515. //Joint Types
  84516. PhysicsJoint.DistanceJoint = 0;
  84517. PhysicsJoint.HingeJoint = 1;
  84518. PhysicsJoint.BallAndSocketJoint = 2;
  84519. PhysicsJoint.WheelJoint = 3;
  84520. PhysicsJoint.SliderJoint = 4;
  84521. //OIMO
  84522. PhysicsJoint.PrismaticJoint = 5;
  84523. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  84524. PhysicsJoint.UniversalJoint = 6;
  84525. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  84526. //Cannon
  84527. //Similar to a Ball-Joint. Different in params
  84528. PhysicsJoint.PointToPointJoint = 8;
  84529. //Cannon only at the moment
  84530. PhysicsJoint.SpringJoint = 9;
  84531. PhysicsJoint.LockJoint = 10;
  84532. return PhysicsJoint;
  84533. }());
  84534. BABYLON.PhysicsJoint = PhysicsJoint;
  84535. /**
  84536. * A class representing a physics distance joint.
  84537. */
  84538. var DistanceJoint = /** @class */ (function (_super) {
  84539. __extends(DistanceJoint, _super);
  84540. function DistanceJoint(jointData) {
  84541. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  84542. }
  84543. /**
  84544. * Update the predefined distance.
  84545. */
  84546. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  84547. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  84548. };
  84549. return DistanceJoint;
  84550. }(PhysicsJoint));
  84551. BABYLON.DistanceJoint = DistanceJoint;
  84552. var MotorEnabledJoint = /** @class */ (function (_super) {
  84553. __extends(MotorEnabledJoint, _super);
  84554. function MotorEnabledJoint(type, jointData) {
  84555. return _super.call(this, type, jointData) || this;
  84556. }
  84557. /**
  84558. * Set the motor values.
  84559. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84560. * @param {number} force the force to apply
  84561. * @param {number} maxForce max force for this motor.
  84562. */
  84563. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  84564. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84565. };
  84566. /**
  84567. * Set the motor's limits.
  84568. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84569. */
  84570. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84571. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84572. };
  84573. return MotorEnabledJoint;
  84574. }(PhysicsJoint));
  84575. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  84576. /**
  84577. * This class represents a single hinge physics joint
  84578. */
  84579. var HingeJoint = /** @class */ (function (_super) {
  84580. __extends(HingeJoint, _super);
  84581. function HingeJoint(jointData) {
  84582. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  84583. }
  84584. /**
  84585. * Set the motor values.
  84586. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84587. * @param {number} force the force to apply
  84588. * @param {number} maxForce max force for this motor.
  84589. */
  84590. HingeJoint.prototype.setMotor = function (force, maxForce) {
  84591. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84592. };
  84593. /**
  84594. * Set the motor's limits.
  84595. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84596. */
  84597. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84598. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84599. };
  84600. return HingeJoint;
  84601. }(MotorEnabledJoint));
  84602. BABYLON.HingeJoint = HingeJoint;
  84603. /**
  84604. * This class represents a dual hinge physics joint (same as wheel joint)
  84605. */
  84606. var Hinge2Joint = /** @class */ (function (_super) {
  84607. __extends(Hinge2Joint, _super);
  84608. function Hinge2Joint(jointData) {
  84609. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  84610. }
  84611. /**
  84612. * Set the motor values.
  84613. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84614. * @param {number} force the force to apply
  84615. * @param {number} maxForce max force for this motor.
  84616. * @param {motorIndex} the motor's index, 0 or 1.
  84617. */
  84618. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  84619. if (motorIndex === void 0) { motorIndex = 0; }
  84620. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  84621. };
  84622. /**
  84623. * Set the motor limits.
  84624. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84625. * @param {number} upperLimit the upper limit
  84626. * @param {number} lowerLimit lower limit
  84627. * @param {motorIndex} the motor's index, 0 or 1.
  84628. */
  84629. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  84630. if (motorIndex === void 0) { motorIndex = 0; }
  84631. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  84632. };
  84633. return Hinge2Joint;
  84634. }(MotorEnabledJoint));
  84635. BABYLON.Hinge2Joint = Hinge2Joint;
  84636. })(BABYLON || (BABYLON = {}));
  84637. //# sourceMappingURL=babylon.physicsJoint.js.map
  84638. var BABYLON;
  84639. (function (BABYLON) {
  84640. var PhysicsImpostor = /** @class */ (function () {
  84641. function PhysicsImpostor(object, type, _options, _scene) {
  84642. if (_options === void 0) { _options = { mass: 0 }; }
  84643. var _this = this;
  84644. this.object = object;
  84645. this.type = type;
  84646. this._options = _options;
  84647. this._scene = _scene;
  84648. this._bodyUpdateRequired = false;
  84649. this._onBeforePhysicsStepCallbacks = new Array();
  84650. this._onAfterPhysicsStepCallbacks = new Array();
  84651. this._onPhysicsCollideCallbacks = [];
  84652. this._deltaPosition = BABYLON.Vector3.Zero();
  84653. this._isDisposed = false;
  84654. //temp variables for parent rotation calculations
  84655. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  84656. this._tmpQuat = new BABYLON.Quaternion();
  84657. this._tmpQuat2 = new BABYLON.Quaternion();
  84658. /**
  84659. * this function is executed by the physics engine.
  84660. */
  84661. this.beforeStep = function () {
  84662. if (!_this._physicsEngine) {
  84663. return;
  84664. }
  84665. _this.object.translate(_this._deltaPosition, -1);
  84666. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  84667. _this.object.computeWorldMatrix(false);
  84668. if (_this.object.parent && _this.object.rotationQuaternion) {
  84669. _this.getParentsRotation();
  84670. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  84671. }
  84672. else {
  84673. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  84674. }
  84675. if (!_this._options.disableBidirectionalTransformation) {
  84676. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  84677. }
  84678. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  84679. func(_this);
  84680. });
  84681. };
  84682. /**
  84683. * this function is executed by the physics engine.
  84684. */
  84685. this.afterStep = function () {
  84686. if (!_this._physicsEngine) {
  84687. return;
  84688. }
  84689. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  84690. func(_this);
  84691. });
  84692. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  84693. // object has now its world rotation. needs to be converted to local.
  84694. if (_this.object.parent && _this.object.rotationQuaternion) {
  84695. _this.getParentsRotation();
  84696. _this._tmpQuat.conjugateInPlace();
  84697. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  84698. }
  84699. // take the position set and make it the absolute position of this object.
  84700. _this.object.setAbsolutePosition(_this.object.position);
  84701. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  84702. _this.object.translate(_this._deltaPosition, 1);
  84703. };
  84704. /**
  84705. * Legacy collision detection event support
  84706. */
  84707. this.onCollideEvent = null;
  84708. //event and body object due to cannon's event-based architecture.
  84709. this.onCollide = function (e) {
  84710. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  84711. return;
  84712. }
  84713. if (!_this._physicsEngine) {
  84714. return;
  84715. }
  84716. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  84717. if (otherImpostor) {
  84718. // Legacy collision detection event support
  84719. if (_this.onCollideEvent) {
  84720. _this.onCollideEvent(_this, otherImpostor);
  84721. }
  84722. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  84723. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  84724. }).forEach(function (obj) {
  84725. obj.callback(_this, otherImpostor);
  84726. });
  84727. }
  84728. };
  84729. //sanity check!
  84730. if (!this.object) {
  84731. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  84732. return;
  84733. }
  84734. //legacy support for old syntax.
  84735. if (!this._scene && object.getScene) {
  84736. this._scene = object.getScene();
  84737. }
  84738. if (!this._scene) {
  84739. return;
  84740. }
  84741. this._physicsEngine = this._scene.getPhysicsEngine();
  84742. if (!this._physicsEngine) {
  84743. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  84744. }
  84745. else {
  84746. //set the object's quaternion, if not set
  84747. if (!this.object.rotationQuaternion) {
  84748. if (this.object.rotation) {
  84749. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  84750. }
  84751. else {
  84752. this.object.rotationQuaternion = new BABYLON.Quaternion();
  84753. }
  84754. }
  84755. //default options params
  84756. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  84757. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  84758. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  84759. this._joints = [];
  84760. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  84761. if (!this.object.parent || this._options.ignoreParent) {
  84762. this._init();
  84763. }
  84764. else if (this.object.parent.physicsImpostor) {
  84765. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  84766. }
  84767. }
  84768. }
  84769. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  84770. get: function () {
  84771. return this._isDisposed;
  84772. },
  84773. enumerable: true,
  84774. configurable: true
  84775. });
  84776. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  84777. get: function () {
  84778. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  84779. },
  84780. set: function (value) {
  84781. this.setMass(value);
  84782. },
  84783. enumerable: true,
  84784. configurable: true
  84785. });
  84786. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  84787. get: function () {
  84788. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  84789. },
  84790. set: function (value) {
  84791. if (!this._physicsEngine) {
  84792. return;
  84793. }
  84794. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  84795. },
  84796. enumerable: true,
  84797. configurable: true
  84798. });
  84799. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  84800. get: function () {
  84801. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  84802. },
  84803. set: function (value) {
  84804. if (!this._physicsEngine) {
  84805. return;
  84806. }
  84807. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  84808. },
  84809. enumerable: true,
  84810. configurable: true
  84811. });
  84812. /**
  84813. * This function will completly initialize this impostor.
  84814. * It will create a new body - but only if this mesh has no parent.
  84815. * If it has, this impostor will not be used other than to define the impostor
  84816. * of the child mesh.
  84817. */
  84818. PhysicsImpostor.prototype._init = function () {
  84819. if (!this._physicsEngine) {
  84820. return;
  84821. }
  84822. this._physicsEngine.removeImpostor(this);
  84823. this.physicsBody = null;
  84824. this._parent = this._parent || this._getPhysicsParent();
  84825. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  84826. this._physicsEngine.addImpostor(this);
  84827. }
  84828. };
  84829. PhysicsImpostor.prototype._getPhysicsParent = function () {
  84830. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  84831. var parentMesh = this.object.parent;
  84832. return parentMesh.physicsImpostor;
  84833. }
  84834. return null;
  84835. };
  84836. /**
  84837. * Should a new body be generated.
  84838. */
  84839. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  84840. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  84841. };
  84842. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  84843. this.forceUpdate();
  84844. };
  84845. /**
  84846. * Force a regeneration of this or the parent's impostor's body.
  84847. * Use under cautious - This will remove all joints already implemented.
  84848. */
  84849. PhysicsImpostor.prototype.forceUpdate = function () {
  84850. this._init();
  84851. if (this.parent && !this._options.ignoreParent) {
  84852. this.parent.forceUpdate();
  84853. }
  84854. };
  84855. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  84856. /*public get mesh(): AbstractMesh {
  84857. return this._mesh;
  84858. }*/
  84859. /**
  84860. * Gets the body that holds this impostor. Either its own, or its parent.
  84861. */
  84862. get: function () {
  84863. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  84864. },
  84865. /**
  84866. * Set the physics body. Used mainly by the physics engine/plugin
  84867. */
  84868. set: function (physicsBody) {
  84869. if (this._physicsBody && this._physicsEngine) {
  84870. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  84871. }
  84872. this._physicsBody = physicsBody;
  84873. this.resetUpdateFlags();
  84874. },
  84875. enumerable: true,
  84876. configurable: true
  84877. });
  84878. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  84879. get: function () {
  84880. return !this._options.ignoreParent && this._parent ? this._parent : null;
  84881. },
  84882. set: function (value) {
  84883. this._parent = value;
  84884. },
  84885. enumerable: true,
  84886. configurable: true
  84887. });
  84888. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  84889. this._bodyUpdateRequired = false;
  84890. };
  84891. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  84892. if (this.object.getBoundingInfo) {
  84893. var q = this.object.rotationQuaternion;
  84894. //reset rotation
  84895. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  84896. //calculate the world matrix with no rotation
  84897. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84898. var boundingInfo = this.object.getBoundingInfo();
  84899. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  84900. //bring back the rotation
  84901. this.object.rotationQuaternion = q;
  84902. //calculate the world matrix with the new rotation
  84903. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84904. return size;
  84905. }
  84906. else {
  84907. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  84908. }
  84909. };
  84910. PhysicsImpostor.prototype.getObjectCenter = function () {
  84911. if (this.object.getBoundingInfo) {
  84912. var boundingInfo = this.object.getBoundingInfo();
  84913. return boundingInfo.boundingBox.centerWorld;
  84914. }
  84915. else {
  84916. return this.object.position;
  84917. }
  84918. };
  84919. /**
  84920. * Get a specific parametes from the options parameter.
  84921. */
  84922. PhysicsImpostor.prototype.getParam = function (paramName) {
  84923. return this._options[paramName];
  84924. };
  84925. /**
  84926. * Sets a specific parameter in the options given to the physics plugin
  84927. */
  84928. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  84929. this._options[paramName] = value;
  84930. this._bodyUpdateRequired = true;
  84931. };
  84932. /**
  84933. * Specifically change the body's mass option. Won't recreate the physics body object
  84934. */
  84935. PhysicsImpostor.prototype.setMass = function (mass) {
  84936. if (this.getParam("mass") !== mass) {
  84937. this.setParam("mass", mass);
  84938. }
  84939. if (this._physicsEngine) {
  84940. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  84941. }
  84942. };
  84943. PhysicsImpostor.prototype.getLinearVelocity = function () {
  84944. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  84945. };
  84946. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  84947. if (this._physicsEngine) {
  84948. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  84949. }
  84950. };
  84951. PhysicsImpostor.prototype.getAngularVelocity = function () {
  84952. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  84953. };
  84954. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  84955. if (this._physicsEngine) {
  84956. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  84957. }
  84958. };
  84959. /**
  84960. * Execute a function with the physics plugin native code.
  84961. * Provide a function the will have two variables - the world object and the physics body object.
  84962. */
  84963. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  84964. if (this._physicsEngine) {
  84965. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  84966. }
  84967. };
  84968. /**
  84969. * Register a function that will be executed before the physics world is stepping forward.
  84970. */
  84971. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  84972. this._onBeforePhysicsStepCallbacks.push(func);
  84973. };
  84974. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  84975. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  84976. if (index > -1) {
  84977. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  84978. }
  84979. else {
  84980. BABYLON.Tools.Warn("Function to remove was not found");
  84981. }
  84982. };
  84983. /**
  84984. * Register a function that will be executed after the physics step
  84985. */
  84986. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  84987. this._onAfterPhysicsStepCallbacks.push(func);
  84988. };
  84989. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  84990. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  84991. if (index > -1) {
  84992. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  84993. }
  84994. else {
  84995. BABYLON.Tools.Warn("Function to remove was not found");
  84996. }
  84997. };
  84998. /**
  84999. * register a function that will be executed when this impostor collides against a different body.
  85000. */
  85001. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  85002. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85003. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  85004. };
  85005. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  85006. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85007. var index = -1;
  85008. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  85009. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  85010. // chcek the arrays match
  85011. var sameList = cbDef.otherImpostors.every(function (impostor) {
  85012. return collidedAgainstList.indexOf(impostor) > -1;
  85013. });
  85014. if (sameList) {
  85015. index = idx;
  85016. }
  85017. return sameList;
  85018. }
  85019. return false;
  85020. });
  85021. if (found) {
  85022. this._onPhysicsCollideCallbacks.splice(index, 1);
  85023. }
  85024. else {
  85025. BABYLON.Tools.Warn("Function to remove was not found");
  85026. }
  85027. };
  85028. PhysicsImpostor.prototype.getParentsRotation = function () {
  85029. var parent = this.object.parent;
  85030. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  85031. while (parent) {
  85032. if (parent.rotationQuaternion) {
  85033. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  85034. }
  85035. else {
  85036. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  85037. }
  85038. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  85039. parent = parent.parent;
  85040. }
  85041. return this._tmpQuat;
  85042. };
  85043. /**
  85044. * Apply a force
  85045. */
  85046. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  85047. if (this._physicsEngine) {
  85048. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  85049. }
  85050. return this;
  85051. };
  85052. /**
  85053. * Apply an impulse
  85054. */
  85055. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  85056. if (this._physicsEngine) {
  85057. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  85058. }
  85059. return this;
  85060. };
  85061. /**
  85062. * A help function to create a joint.
  85063. */
  85064. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  85065. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  85066. this.addJoint(otherImpostor, joint);
  85067. return this;
  85068. };
  85069. /**
  85070. * Add a joint to this impostor with a different impostor.
  85071. */
  85072. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  85073. this._joints.push({
  85074. otherImpostor: otherImpostor,
  85075. joint: joint
  85076. });
  85077. if (this._physicsEngine) {
  85078. this._physicsEngine.addJoint(this, otherImpostor, joint);
  85079. }
  85080. return this;
  85081. };
  85082. /**
  85083. * Will keep this body still, in a sleep mode.
  85084. */
  85085. PhysicsImpostor.prototype.sleep = function () {
  85086. if (this._physicsEngine) {
  85087. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  85088. }
  85089. return this;
  85090. };
  85091. /**
  85092. * Wake the body up.
  85093. */
  85094. PhysicsImpostor.prototype.wakeUp = function () {
  85095. if (this._physicsEngine) {
  85096. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  85097. }
  85098. return this;
  85099. };
  85100. PhysicsImpostor.prototype.clone = function (newObject) {
  85101. if (!newObject)
  85102. return null;
  85103. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  85104. };
  85105. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  85106. var _this = this;
  85107. //no dispose if no physics engine is available.
  85108. if (!this._physicsEngine) {
  85109. return;
  85110. }
  85111. this._joints.forEach(function (j) {
  85112. if (_this._physicsEngine) {
  85113. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  85114. }
  85115. });
  85116. //dispose the physics body
  85117. this._physicsEngine.removeImpostor(this);
  85118. if (this.parent) {
  85119. this.parent.forceUpdate();
  85120. }
  85121. else {
  85122. /*this._object.getChildMeshes().forEach(function(mesh) {
  85123. if (mesh.physicsImpostor) {
  85124. if (disposeChildren) {
  85125. mesh.physicsImpostor.dispose();
  85126. mesh.physicsImpostor = null;
  85127. }
  85128. }
  85129. })*/
  85130. }
  85131. this._isDisposed = true;
  85132. };
  85133. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  85134. this._deltaPosition.copyFrom(position);
  85135. };
  85136. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  85137. if (!this._deltaRotation) {
  85138. this._deltaRotation = new BABYLON.Quaternion();
  85139. }
  85140. this._deltaRotation.copyFrom(rotation);
  85141. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  85142. };
  85143. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  85144. if (this._physicsEngine) {
  85145. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  85146. }
  85147. return this;
  85148. };
  85149. PhysicsImpostor.prototype.getRadius = function () {
  85150. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  85151. };
  85152. /**
  85153. * Sync a bone with this impostor
  85154. * @param bone The bone to sync to the impostor.
  85155. * @param boneMesh The mesh that the bone is influencing.
  85156. * @param jointPivot The pivot of the joint / bone in local space.
  85157. * @param distToJoint Optional distance from the impostor to the joint.
  85158. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85159. */
  85160. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  85161. var tempVec = PhysicsImpostor._tmpVecs[0];
  85162. var mesh = this.object;
  85163. if (mesh.rotationQuaternion) {
  85164. if (adjustRotation) {
  85165. var tempQuat = PhysicsImpostor._tmpQuat;
  85166. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  85167. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  85168. }
  85169. else {
  85170. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  85171. }
  85172. }
  85173. tempVec.x = 0;
  85174. tempVec.y = 0;
  85175. tempVec.z = 0;
  85176. if (jointPivot) {
  85177. tempVec.x = jointPivot.x;
  85178. tempVec.y = jointPivot.y;
  85179. tempVec.z = jointPivot.z;
  85180. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  85181. if (distToJoint === undefined || distToJoint === null) {
  85182. distToJoint = jointPivot.length();
  85183. }
  85184. tempVec.x *= distToJoint;
  85185. tempVec.y *= distToJoint;
  85186. tempVec.z *= distToJoint;
  85187. }
  85188. if (bone.getParent()) {
  85189. tempVec.addInPlace(mesh.getAbsolutePosition());
  85190. bone.setAbsolutePosition(tempVec, boneMesh);
  85191. }
  85192. else {
  85193. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  85194. boneMesh.position.x -= tempVec.x;
  85195. boneMesh.position.y -= tempVec.y;
  85196. boneMesh.position.z -= tempVec.z;
  85197. }
  85198. };
  85199. /**
  85200. * Sync impostor to a bone
  85201. * @param bone The bone that the impostor will be synced to.
  85202. * @param boneMesh The mesh that the bone is influencing.
  85203. * @param jointPivot The pivot of the joint / bone in local space.
  85204. * @param distToJoint Optional distance from the impostor to the joint.
  85205. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85206. * @param boneAxis Optional vector3 axis the bone is aligned with
  85207. */
  85208. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  85209. var mesh = this.object;
  85210. if (mesh.rotationQuaternion) {
  85211. if (adjustRotation) {
  85212. var tempQuat = PhysicsImpostor._tmpQuat;
  85213. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  85214. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  85215. }
  85216. else {
  85217. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  85218. }
  85219. }
  85220. var pos = PhysicsImpostor._tmpVecs[0];
  85221. var boneDir = PhysicsImpostor._tmpVecs[1];
  85222. if (!boneAxis) {
  85223. boneAxis = PhysicsImpostor._tmpVecs[2];
  85224. boneAxis.x = 0;
  85225. boneAxis.y = 1;
  85226. boneAxis.z = 0;
  85227. }
  85228. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  85229. bone.getAbsolutePositionToRef(boneMesh, pos);
  85230. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  85231. distToJoint = jointPivot.length();
  85232. }
  85233. if (distToJoint !== undefined && distToJoint !== null) {
  85234. pos.x += boneDir.x * distToJoint;
  85235. pos.y += boneDir.y * distToJoint;
  85236. pos.z += boneDir.z * distToJoint;
  85237. }
  85238. mesh.setAbsolutePosition(pos);
  85239. };
  85240. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  85241. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  85242. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85243. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  85244. //Impostor types
  85245. PhysicsImpostor.NoImpostor = 0;
  85246. PhysicsImpostor.SphereImpostor = 1;
  85247. PhysicsImpostor.BoxImpostor = 2;
  85248. PhysicsImpostor.PlaneImpostor = 3;
  85249. PhysicsImpostor.MeshImpostor = 4;
  85250. PhysicsImpostor.CylinderImpostor = 7;
  85251. PhysicsImpostor.ParticleImpostor = 8;
  85252. PhysicsImpostor.HeightmapImpostor = 9;
  85253. return PhysicsImpostor;
  85254. }());
  85255. BABYLON.PhysicsImpostor = PhysicsImpostor;
  85256. })(BABYLON || (BABYLON = {}));
  85257. //# sourceMappingURL=babylon.physicsImpostor.js.map
  85258. var BABYLON;
  85259. (function (BABYLON) {
  85260. var PhysicsEngine = /** @class */ (function () {
  85261. function PhysicsEngine(gravity, _physicsPlugin) {
  85262. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  85263. this._physicsPlugin = _physicsPlugin;
  85264. //new methods and parameters
  85265. this._impostors = [];
  85266. this._joints = [];
  85267. if (!this._physicsPlugin.isSupported()) {
  85268. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  85269. + "Please make sure it is included.");
  85270. }
  85271. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  85272. this.setGravity(gravity);
  85273. this.setTimeStep();
  85274. }
  85275. PhysicsEngine.prototype.setGravity = function (gravity) {
  85276. this.gravity = gravity;
  85277. this._physicsPlugin.setGravity(this.gravity);
  85278. };
  85279. /**
  85280. * Set the time step of the physics engine.
  85281. * default is 1/60.
  85282. * To slow it down, enter 1/600 for example.
  85283. * To speed it up, 1/30
  85284. * @param {number} newTimeStep the new timestep to apply to this world.
  85285. */
  85286. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  85287. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  85288. this._physicsPlugin.setTimeStep(newTimeStep);
  85289. };
  85290. /**
  85291. * Get the time step of the physics engine.
  85292. */
  85293. PhysicsEngine.prototype.getTimeStep = function () {
  85294. return this._physicsPlugin.getTimeStep();
  85295. };
  85296. PhysicsEngine.prototype.dispose = function () {
  85297. this._impostors.forEach(function (impostor) {
  85298. impostor.dispose();
  85299. });
  85300. this._physicsPlugin.dispose();
  85301. };
  85302. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  85303. return this._physicsPlugin.name;
  85304. };
  85305. /**
  85306. * Adding a new impostor for the impostor tracking.
  85307. * This will be done by the impostor itself.
  85308. * @param {PhysicsImpostor} impostor the impostor to add
  85309. */
  85310. PhysicsEngine.prototype.addImpostor = function (impostor) {
  85311. impostor.uniqueId = this._impostors.push(impostor);
  85312. //if no parent, generate the body
  85313. if (!impostor.parent) {
  85314. this._physicsPlugin.generatePhysicsBody(impostor);
  85315. }
  85316. };
  85317. /**
  85318. * Remove an impostor from the engine.
  85319. * This impostor and its mesh will not longer be updated by the physics engine.
  85320. * @param {PhysicsImpostor} impostor the impostor to remove
  85321. */
  85322. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  85323. var index = this._impostors.indexOf(impostor);
  85324. if (index > -1) {
  85325. var removed = this._impostors.splice(index, 1);
  85326. //Is it needed?
  85327. if (removed.length) {
  85328. //this will also remove it from the world.
  85329. removed[0].physicsBody = null;
  85330. }
  85331. }
  85332. };
  85333. /**
  85334. * Add a joint to the physics engine
  85335. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  85336. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  85337. * @param {PhysicsJoint} the joint that will connect both impostors.
  85338. */
  85339. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  85340. var impostorJoint = {
  85341. mainImpostor: mainImpostor,
  85342. connectedImpostor: connectedImpostor,
  85343. joint: joint
  85344. };
  85345. joint.physicsPlugin = this._physicsPlugin;
  85346. this._joints.push(impostorJoint);
  85347. this._physicsPlugin.generateJoint(impostorJoint);
  85348. };
  85349. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  85350. var matchingJoints = this._joints.filter(function (impostorJoint) {
  85351. return (impostorJoint.connectedImpostor === connectedImpostor
  85352. && impostorJoint.joint === joint
  85353. && impostorJoint.mainImpostor === mainImpostor);
  85354. });
  85355. if (matchingJoints.length) {
  85356. this._physicsPlugin.removeJoint(matchingJoints[0]);
  85357. //TODO remove it from the list as well
  85358. }
  85359. };
  85360. /**
  85361. * Called by the scene. no need to call it.
  85362. */
  85363. PhysicsEngine.prototype._step = function (delta) {
  85364. var _this = this;
  85365. //check if any mesh has no body / requires an update
  85366. this._impostors.forEach(function (impostor) {
  85367. if (impostor.isBodyInitRequired()) {
  85368. _this._physicsPlugin.generatePhysicsBody(impostor);
  85369. }
  85370. });
  85371. if (delta > 0.1) {
  85372. delta = 0.1;
  85373. }
  85374. else if (delta <= 0) {
  85375. delta = 1.0 / 60.0;
  85376. }
  85377. this._physicsPlugin.executeStep(delta, this._impostors);
  85378. };
  85379. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  85380. return this._physicsPlugin;
  85381. };
  85382. PhysicsEngine.prototype.getImpostors = function () {
  85383. return this._impostors;
  85384. };
  85385. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  85386. for (var i = 0; i < this._impostors.length; ++i) {
  85387. if (this._impostors[i].object === object) {
  85388. return this._impostors[i];
  85389. }
  85390. }
  85391. return null;
  85392. };
  85393. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  85394. for (var i = 0; i < this._impostors.length; ++i) {
  85395. if (this._impostors[i].physicsBody === body) {
  85396. return this._impostors[i];
  85397. }
  85398. }
  85399. return null;
  85400. };
  85401. // Statics
  85402. PhysicsEngine.Epsilon = 0.001;
  85403. return PhysicsEngine;
  85404. }());
  85405. BABYLON.PhysicsEngine = PhysicsEngine;
  85406. })(BABYLON || (BABYLON = {}));
  85407. //# sourceMappingURL=babylon.physicsEngine.js.map
  85408. var BABYLON;
  85409. (function (BABYLON) {
  85410. var PhysicsHelper = /** @class */ (function () {
  85411. function PhysicsHelper(scene) {
  85412. this._scene = scene;
  85413. this._physicsEngine = this._scene.getPhysicsEngine();
  85414. if (!this._physicsEngine) {
  85415. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  85416. }
  85417. }
  85418. /**
  85419. * @param {Vector3} origin the origin of the explosion
  85420. * @param {number} radius the explosion radius
  85421. * @param {number} strength the explosion strength
  85422. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85423. */
  85424. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  85425. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85426. if (!this._physicsEngine) {
  85427. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  85428. return null;
  85429. }
  85430. var impostors = this._physicsEngine.getImpostors();
  85431. if (impostors.length === 0) {
  85432. return null;
  85433. }
  85434. var event = new PhysicsRadialExplosionEvent(this._scene);
  85435. impostors.forEach(function (impostor) {
  85436. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85437. if (!impostorForceAndContactPoint) {
  85438. return;
  85439. }
  85440. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85441. });
  85442. event.dispose(false);
  85443. return event;
  85444. };
  85445. /**
  85446. * @param {Vector3} origin the origin of the explosion
  85447. * @param {number} radius the explosion radius
  85448. * @param {number} strength the explosion strength
  85449. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85450. */
  85451. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  85452. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85453. if (!this._physicsEngine) {
  85454. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85455. return null;
  85456. }
  85457. var impostors = this._physicsEngine.getImpostors();
  85458. if (impostors.length === 0) {
  85459. return null;
  85460. }
  85461. var event = new PhysicsRadialExplosionEvent(this._scene);
  85462. impostors.forEach(function (impostor) {
  85463. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85464. if (!impostorForceAndContactPoint) {
  85465. return;
  85466. }
  85467. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85468. });
  85469. event.dispose(false);
  85470. return event;
  85471. };
  85472. /**
  85473. * @param {Vector3} origin the origin of the explosion
  85474. * @param {number} radius the explosion radius
  85475. * @param {number} strength the explosion strength
  85476. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85477. */
  85478. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  85479. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85480. if (!this._physicsEngine) {
  85481. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85482. return null;
  85483. }
  85484. var impostors = this._physicsEngine.getImpostors();
  85485. if (impostors.length === 0) {
  85486. return null;
  85487. }
  85488. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  85489. event.dispose(false);
  85490. return event;
  85491. };
  85492. /**
  85493. * @param {Vector3} origin the origin of the updraft
  85494. * @param {number} radius the radius of the updraft
  85495. * @param {number} strength the strength of the updraft
  85496. * @param {number} height the height of the updraft
  85497. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  85498. */
  85499. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  85500. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  85501. if (!this._physicsEngine) {
  85502. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85503. return null;
  85504. }
  85505. if (this._physicsEngine.getImpostors().length === 0) {
  85506. return null;
  85507. }
  85508. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  85509. event.dispose(false);
  85510. return event;
  85511. };
  85512. /**
  85513. * @param {Vector3} origin the of the vortex
  85514. * @param {number} radius the radius of the vortex
  85515. * @param {number} strength the strength of the vortex
  85516. * @param {number} height the height of the vortex
  85517. */
  85518. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  85519. if (!this._physicsEngine) {
  85520. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85521. return null;
  85522. }
  85523. if (this._physicsEngine.getImpostors().length === 0) {
  85524. return null;
  85525. }
  85526. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  85527. event.dispose(false);
  85528. return event;
  85529. };
  85530. return PhysicsHelper;
  85531. }());
  85532. BABYLON.PhysicsHelper = PhysicsHelper;
  85533. /***** Radial explosion *****/
  85534. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  85535. function PhysicsRadialExplosionEvent(scene) {
  85536. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  85537. this._rays = [];
  85538. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  85539. this._scene = scene;
  85540. }
  85541. /**
  85542. * Returns the data related to the radial explosion event (sphere & rays).
  85543. * @returns {PhysicsRadialExplosionEventData}
  85544. */
  85545. PhysicsRadialExplosionEvent.prototype.getData = function () {
  85546. this._dataFetched = true;
  85547. return {
  85548. sphere: this._sphere,
  85549. rays: this._rays,
  85550. };
  85551. };
  85552. /**
  85553. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  85554. * @param impostor
  85555. * @param {Vector3} origin the origin of the explosion
  85556. * @param {number} radius the explosion radius
  85557. * @param {number} strength the explosion strength
  85558. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  85559. * @returns {Nullable<PhysicsForceAndContactPoint>}
  85560. */
  85561. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  85562. if (impostor.mass === 0) {
  85563. return null;
  85564. }
  85565. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  85566. return null;
  85567. }
  85568. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85569. return null;
  85570. }
  85571. var impostorObjectCenter = impostor.getObjectCenter();
  85572. var direction = impostorObjectCenter.subtract(origin);
  85573. var ray = new BABYLON.Ray(origin, direction, radius);
  85574. this._rays.push(ray);
  85575. var hit = ray.intersectsMesh(impostor.object);
  85576. var contactPoint = hit.pickedPoint;
  85577. if (!contactPoint) {
  85578. return null;
  85579. }
  85580. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  85581. if (distanceFromOrigin > radius) {
  85582. return null;
  85583. }
  85584. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  85585. ? strength
  85586. : strength * (1 - (distanceFromOrigin / radius));
  85587. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85588. return { force: force, contactPoint: contactPoint };
  85589. };
  85590. /**
  85591. * Disposes the sphere.
  85592. * @param {bolean} force
  85593. */
  85594. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  85595. var _this = this;
  85596. if (force === void 0) { force = true; }
  85597. if (force) {
  85598. this._sphere.dispose();
  85599. }
  85600. else {
  85601. setTimeout(function () {
  85602. if (!_this._dataFetched) {
  85603. _this._sphere.dispose();
  85604. }
  85605. }, 0);
  85606. }
  85607. };
  85608. /*** Helpers ***/
  85609. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  85610. if (!this._sphere) {
  85611. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  85612. this._sphere.isVisible = false;
  85613. }
  85614. };
  85615. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  85616. var impostorObject = impostor.object;
  85617. this._prepareSphere();
  85618. this._sphere.position = origin;
  85619. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  85620. this._sphere._updateBoundingInfo();
  85621. this._sphere.computeWorldMatrix(true);
  85622. return this._sphere.intersectsMesh(impostorObject, true);
  85623. };
  85624. return PhysicsRadialExplosionEvent;
  85625. }());
  85626. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  85627. /***** Gravitational Field *****/
  85628. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  85629. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  85630. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85631. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85632. this._physicsHelper = physicsHelper;
  85633. this._scene = scene;
  85634. this._origin = origin;
  85635. this._radius = radius;
  85636. this._strength = strength;
  85637. this._falloff = falloff;
  85638. this._tickCallback = this._tick.bind(this);
  85639. }
  85640. /**
  85641. * Returns the data related to the gravitational field event (sphere).
  85642. * @returns {PhysicsGravitationalFieldEventData}
  85643. */
  85644. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  85645. this._dataFetched = true;
  85646. return {
  85647. sphere: this._sphere,
  85648. };
  85649. };
  85650. /**
  85651. * Enables the gravitational field.
  85652. */
  85653. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  85654. this._tickCallback.call(this);
  85655. this._scene.registerBeforeRender(this._tickCallback);
  85656. };
  85657. /**
  85658. * Disables the gravitational field.
  85659. */
  85660. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  85661. this._scene.unregisterBeforeRender(this._tickCallback);
  85662. };
  85663. /**
  85664. * Disposes the sphere.
  85665. * @param {bolean} force
  85666. */
  85667. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  85668. var _this = this;
  85669. if (force === void 0) { force = true; }
  85670. if (force) {
  85671. this._sphere.dispose();
  85672. }
  85673. else {
  85674. setTimeout(function () {
  85675. if (!_this._dataFetched) {
  85676. _this._sphere.dispose();
  85677. }
  85678. }, 0);
  85679. }
  85680. };
  85681. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  85682. // Since the params won't change, we fetch the event only once
  85683. if (this._sphere) {
  85684. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85685. }
  85686. else {
  85687. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85688. if (radialExplosionEvent) {
  85689. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  85690. }
  85691. }
  85692. };
  85693. return PhysicsGravitationalFieldEvent;
  85694. }());
  85695. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  85696. /***** Updraft *****/
  85697. var PhysicsUpdraftEvent = /** @class */ (function () {
  85698. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  85699. this._scene = _scene;
  85700. this._origin = _origin;
  85701. this._radius = _radius;
  85702. this._strength = _strength;
  85703. this._height = _height;
  85704. this._updraftMode = _updraftMode;
  85705. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85706. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  85707. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85708. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85709. this._physicsEngine = this._scene.getPhysicsEngine();
  85710. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85711. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85712. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85713. this._originDirection = this._origin.subtract(this._originTop).normalize();
  85714. }
  85715. this._tickCallback = this._tick.bind(this);
  85716. }
  85717. /**
  85718. * Returns the data related to the updraft event (cylinder).
  85719. * @returns {PhysicsUpdraftEventData}
  85720. */
  85721. PhysicsUpdraftEvent.prototype.getData = function () {
  85722. this._dataFetched = true;
  85723. return {
  85724. cylinder: this._cylinder,
  85725. };
  85726. };
  85727. /**
  85728. * Enables the updraft.
  85729. */
  85730. PhysicsUpdraftEvent.prototype.enable = function () {
  85731. this._tickCallback.call(this);
  85732. this._scene.registerBeforeRender(this._tickCallback);
  85733. };
  85734. /**
  85735. * Disables the cortex.
  85736. */
  85737. PhysicsUpdraftEvent.prototype.disable = function () {
  85738. this._scene.unregisterBeforeRender(this._tickCallback);
  85739. };
  85740. /**
  85741. * Disposes the sphere.
  85742. * @param {bolean} force
  85743. */
  85744. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  85745. var _this = this;
  85746. if (force === void 0) { force = true; }
  85747. if (force) {
  85748. this._cylinder.dispose();
  85749. }
  85750. else {
  85751. setTimeout(function () {
  85752. if (!_this._dataFetched) {
  85753. _this._cylinder.dispose();
  85754. }
  85755. }, 0);
  85756. }
  85757. };
  85758. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85759. if (impostor.mass === 0) {
  85760. return null;
  85761. }
  85762. if (!this._intersectsWithCylinder(impostor)) {
  85763. return null;
  85764. }
  85765. var impostorObjectCenter = impostor.getObjectCenter();
  85766. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85767. var direction = this._originDirection;
  85768. }
  85769. else {
  85770. var direction = impostorObjectCenter.subtract(this._originTop);
  85771. }
  85772. var multiplier = this._strength * -1;
  85773. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85774. return { force: force, contactPoint: impostorObjectCenter };
  85775. };
  85776. PhysicsUpdraftEvent.prototype._tick = function () {
  85777. var _this = this;
  85778. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85779. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85780. if (!impostorForceAndContactPoint) {
  85781. return;
  85782. }
  85783. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85784. });
  85785. };
  85786. /*** Helpers ***/
  85787. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  85788. if (!this._cylinder) {
  85789. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  85790. height: this._height,
  85791. diameter: this._radius * 2,
  85792. }, this._scene);
  85793. this._cylinder.isVisible = false;
  85794. }
  85795. };
  85796. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  85797. var impostorObject = impostor.object;
  85798. this._prepareCylinder();
  85799. this._cylinder.position = this._cylinderPosition;
  85800. return this._cylinder.intersectsMesh(impostorObject, true);
  85801. };
  85802. return PhysicsUpdraftEvent;
  85803. }());
  85804. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  85805. /***** Vortex *****/
  85806. var PhysicsVortexEvent = /** @class */ (function () {
  85807. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  85808. this._scene = _scene;
  85809. this._origin = _origin;
  85810. this._radius = _radius;
  85811. this._strength = _strength;
  85812. this._height = _height;
  85813. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85814. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  85815. this._updraftMultiplier = 0.02;
  85816. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85817. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85818. this._physicsEngine = this._scene.getPhysicsEngine();
  85819. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85820. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85821. this._tickCallback = this._tick.bind(this);
  85822. }
  85823. /**
  85824. * Returns the data related to the vortex event (cylinder).
  85825. * @returns {PhysicsVortexEventData}
  85826. */
  85827. PhysicsVortexEvent.prototype.getData = function () {
  85828. this._dataFetched = true;
  85829. return {
  85830. cylinder: this._cylinder,
  85831. };
  85832. };
  85833. /**
  85834. * Enables the vortex.
  85835. */
  85836. PhysicsVortexEvent.prototype.enable = function () {
  85837. this._tickCallback.call(this);
  85838. this._scene.registerBeforeRender(this._tickCallback);
  85839. };
  85840. /**
  85841. * Disables the cortex.
  85842. */
  85843. PhysicsVortexEvent.prototype.disable = function () {
  85844. this._scene.unregisterBeforeRender(this._tickCallback);
  85845. };
  85846. /**
  85847. * Disposes the sphere.
  85848. * @param {bolean} force
  85849. */
  85850. PhysicsVortexEvent.prototype.dispose = function (force) {
  85851. var _this = this;
  85852. if (force === void 0) { force = true; }
  85853. if (force) {
  85854. this._cylinder.dispose();
  85855. }
  85856. else {
  85857. setTimeout(function () {
  85858. if (!_this._dataFetched) {
  85859. _this._cylinder.dispose();
  85860. }
  85861. }, 0);
  85862. }
  85863. };
  85864. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85865. if (impostor.mass === 0) {
  85866. return null;
  85867. }
  85868. if (!this._intersectsWithCylinder(impostor)) {
  85869. return null;
  85870. }
  85871. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85872. return null;
  85873. }
  85874. var impostorObjectCenter = impostor.getObjectCenter();
  85875. 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)
  85876. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  85877. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  85878. var hit = ray.intersectsMesh(impostor.object);
  85879. var contactPoint = hit.pickedPoint;
  85880. if (!contactPoint) {
  85881. return null;
  85882. }
  85883. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  85884. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  85885. var directionToOrigin = contactPoint.normalize();
  85886. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85887. directionToOrigin = directionToOrigin.negate();
  85888. }
  85889. // TODO: find a more physically based solution
  85890. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85891. var forceX = directionToOrigin.x * this._strength / 8;
  85892. var forceY = directionToOrigin.y * this._updraftMultiplier;
  85893. var forceZ = directionToOrigin.z * this._strength / 8;
  85894. }
  85895. else {
  85896. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  85897. var forceY = this._originTop.y * this._updraftMultiplier;
  85898. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  85899. }
  85900. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  85901. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  85902. return { force: force, contactPoint: impostorObjectCenter };
  85903. };
  85904. PhysicsVortexEvent.prototype._tick = function () {
  85905. var _this = this;
  85906. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85907. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85908. if (!impostorForceAndContactPoint) {
  85909. return;
  85910. }
  85911. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85912. });
  85913. };
  85914. /*** Helpers ***/
  85915. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  85916. if (!this._cylinder) {
  85917. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  85918. height: this._height,
  85919. diameter: this._radius * 2,
  85920. }, this._scene);
  85921. this._cylinder.isVisible = false;
  85922. }
  85923. };
  85924. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  85925. var impostorObject = impostor.object;
  85926. this._prepareCylinder();
  85927. this._cylinder.position = this._cylinderPosition;
  85928. return this._cylinder.intersectsMesh(impostorObject, true);
  85929. };
  85930. return PhysicsVortexEvent;
  85931. }());
  85932. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  85933. /***** Enums *****/
  85934. /**
  85935. * The strenght of the force in correspondence to the distance of the affected object
  85936. */
  85937. var PhysicsRadialImpulseFalloff;
  85938. (function (PhysicsRadialImpulseFalloff) {
  85939. /** Defines that impulse is constant in strength across it's whole radius */
  85940. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  85941. /** DEfines that impulse gets weaker if it's further from the origin */
  85942. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  85943. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  85944. /**
  85945. * The strenght of the force in correspondence to the distance of the affected object
  85946. */
  85947. var PhysicsUpdraftMode;
  85948. (function (PhysicsUpdraftMode) {
  85949. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  85950. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  85951. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  85952. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  85953. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  85954. })(BABYLON || (BABYLON = {}));
  85955. //# sourceMappingURL=babylon.physicsHelper.js.map
  85956. var BABYLON;
  85957. (function (BABYLON) {
  85958. var CannonJSPlugin = /** @class */ (function () {
  85959. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  85960. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  85961. if (iterations === void 0) { iterations = 10; }
  85962. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  85963. this.name = "CannonJSPlugin";
  85964. this._physicsMaterials = new Array();
  85965. this._fixedTimeStep = 1 / 60;
  85966. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  85967. this.BJSCANNON = CANNON;
  85968. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  85969. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  85970. this._tmpPosition = BABYLON.Vector3.Zero();
  85971. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  85972. this._tmpUnityRotation = new BABYLON.Quaternion();
  85973. if (!this.isSupported()) {
  85974. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  85975. return;
  85976. }
  85977. this._extendNamespace();
  85978. this.world = new this.BJSCANNON.World();
  85979. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  85980. this.world.solver.iterations = iterations;
  85981. }
  85982. CannonJSPlugin.prototype.setGravity = function (gravity) {
  85983. this.world.gravity.copy(gravity);
  85984. };
  85985. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  85986. this._fixedTimeStep = timeStep;
  85987. };
  85988. CannonJSPlugin.prototype.getTimeStep = function () {
  85989. return this._fixedTimeStep;
  85990. };
  85991. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  85992. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  85993. };
  85994. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85995. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85996. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85997. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  85998. };
  85999. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86000. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86001. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86002. impostor.physicsBody.applyForce(impulse, worldPoint);
  86003. };
  86004. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86005. //parent-child relationship. Does this impostor has a parent impostor?
  86006. if (impostor.parent) {
  86007. if (impostor.physicsBody) {
  86008. this.removePhysicsBody(impostor);
  86009. //TODO is that needed?
  86010. impostor.forceUpdate();
  86011. }
  86012. return;
  86013. }
  86014. //should a new body be created for this impostor?
  86015. if (impostor.isBodyInitRequired()) {
  86016. var shape = this._createShape(impostor);
  86017. //unregister events, if body is being changed
  86018. var oldBody = impostor.physicsBody;
  86019. if (oldBody) {
  86020. this.removePhysicsBody(impostor);
  86021. }
  86022. //create the body and material
  86023. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  86024. var bodyCreationObject = {
  86025. mass: impostor.getParam("mass"),
  86026. material: material
  86027. };
  86028. // A simple extend, in case native options were used.
  86029. var nativeOptions = impostor.getParam("nativeOptions");
  86030. for (var key in nativeOptions) {
  86031. if (nativeOptions.hasOwnProperty(key)) {
  86032. bodyCreationObject[key] = nativeOptions[key];
  86033. }
  86034. }
  86035. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  86036. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  86037. this.world.addEventListener("preStep", impostor.beforeStep);
  86038. this.world.addEventListener("postStep", impostor.afterStep);
  86039. impostor.physicsBody.addShape(shape);
  86040. this.world.add(impostor.physicsBody);
  86041. //try to keep the body moving in the right direction by taking old properties.
  86042. //Should be tested!
  86043. if (oldBody) {
  86044. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  86045. impostor.physicsBody[param].copy(oldBody[param]);
  86046. });
  86047. }
  86048. this._processChildMeshes(impostor);
  86049. }
  86050. //now update the body's transformation
  86051. this._updatePhysicsBodyTransformation(impostor);
  86052. };
  86053. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  86054. var _this = this;
  86055. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  86056. var currentRotation = mainImpostor.object.rotationQuaternion;
  86057. if (meshChildren.length) {
  86058. var processMesh = function (localPosition, mesh) {
  86059. if (!currentRotation || !mesh.rotationQuaternion) {
  86060. return;
  86061. }
  86062. var childImpostor = mesh.getPhysicsImpostor();
  86063. if (childImpostor) {
  86064. var parent = childImpostor.parent;
  86065. if (parent !== mainImpostor) {
  86066. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  86067. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  86068. if (childImpostor.physicsBody) {
  86069. _this.removePhysicsBody(childImpostor);
  86070. childImpostor.physicsBody = null;
  86071. }
  86072. childImpostor.parent = mainImpostor;
  86073. childImpostor.resetUpdateFlags();
  86074. 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));
  86075. //Add the mass of the children.
  86076. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  86077. }
  86078. }
  86079. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  86080. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  86081. };
  86082. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  86083. }
  86084. };
  86085. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86086. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  86087. this.world.removeEventListener("preStep", impostor.beforeStep);
  86088. this.world.removeEventListener("postStep", impostor.afterStep);
  86089. this.world.remove(impostor.physicsBody);
  86090. };
  86091. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86092. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86093. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86094. if (!mainBody || !connectedBody) {
  86095. return;
  86096. }
  86097. var constraint;
  86098. var jointData = impostorJoint.joint.jointData;
  86099. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  86100. var constraintData = {
  86101. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  86102. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  86103. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  86104. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  86105. maxForce: jointData.nativeParams.maxForce,
  86106. collideConnected: !!jointData.collision
  86107. };
  86108. switch (impostorJoint.joint.type) {
  86109. case BABYLON.PhysicsJoint.HingeJoint:
  86110. case BABYLON.PhysicsJoint.Hinge2Joint:
  86111. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  86112. break;
  86113. case BABYLON.PhysicsJoint.DistanceJoint:
  86114. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  86115. break;
  86116. case BABYLON.PhysicsJoint.SpringJoint:
  86117. var springData = jointData;
  86118. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  86119. restLength: springData.length,
  86120. stiffness: springData.stiffness,
  86121. damping: springData.damping,
  86122. localAnchorA: constraintData.pivotA,
  86123. localAnchorB: constraintData.pivotB
  86124. });
  86125. break;
  86126. case BABYLON.PhysicsJoint.LockJoint:
  86127. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  86128. break;
  86129. case BABYLON.PhysicsJoint.PointToPointJoint:
  86130. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86131. default:
  86132. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  86133. break;
  86134. }
  86135. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  86136. constraint.collideConnected = !!jointData.collision;
  86137. impostorJoint.joint.physicsJoint = constraint;
  86138. //don't add spring as constraint, as it is not one.
  86139. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  86140. this.world.addConstraint(constraint);
  86141. }
  86142. else {
  86143. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  86144. constraint.applyForce();
  86145. });
  86146. }
  86147. };
  86148. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86149. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  86150. };
  86151. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  86152. var index;
  86153. var mat;
  86154. for (index = 0; index < this._physicsMaterials.length; index++) {
  86155. mat = this._physicsMaterials[index];
  86156. if (mat.friction === friction && mat.restitution === restitution) {
  86157. return mat;
  86158. }
  86159. }
  86160. var currentMat = new this.BJSCANNON.Material(name);
  86161. currentMat.friction = friction;
  86162. currentMat.restitution = restitution;
  86163. this._physicsMaterials.push(currentMat);
  86164. return currentMat;
  86165. };
  86166. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  86167. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  86168. };
  86169. CannonJSPlugin.prototype._createShape = function (impostor) {
  86170. var object = impostor.object;
  86171. var returnValue;
  86172. var extendSize = impostor.getObjectExtendSize();
  86173. switch (impostor.type) {
  86174. case BABYLON.PhysicsImpostor.SphereImpostor:
  86175. var radiusX = extendSize.x;
  86176. var radiusY = extendSize.y;
  86177. var radiusZ = extendSize.z;
  86178. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  86179. break;
  86180. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  86181. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86182. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  86183. break;
  86184. case BABYLON.PhysicsImpostor.BoxImpostor:
  86185. var box = extendSize.scale(0.5);
  86186. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  86187. break;
  86188. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86189. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  86190. returnValue = new this.BJSCANNON.Plane();
  86191. break;
  86192. case BABYLON.PhysicsImpostor.MeshImpostor:
  86193. // should transform the vertex data to world coordinates!!
  86194. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  86195. var rawFaces = object.getIndices ? object.getIndices() : [];
  86196. if (!rawVerts)
  86197. return;
  86198. // get only scale! so the object could transform correctly.
  86199. var oldPosition = object.position.clone();
  86200. var oldRotation = object.rotation && object.rotation.clone();
  86201. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  86202. object.position.copyFromFloats(0, 0, 0);
  86203. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86204. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86205. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86206. var transform = object.computeWorldMatrix(true);
  86207. // convert rawVerts to object space
  86208. var temp = new Array();
  86209. var index;
  86210. for (index = 0; index < rawVerts.length; index += 3) {
  86211. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  86212. }
  86213. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  86214. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  86215. //now set back the transformation!
  86216. object.position.copyFrom(oldPosition);
  86217. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  86218. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  86219. break;
  86220. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  86221. var oldPosition2 = object.position.clone();
  86222. var oldRotation2 = object.rotation && object.rotation.clone();
  86223. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  86224. object.position.copyFromFloats(0, 0, 0);
  86225. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86226. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86227. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86228. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  86229. returnValue = this._createHeightmap(object);
  86230. object.position.copyFrom(oldPosition2);
  86231. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  86232. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  86233. object.computeWorldMatrix(true);
  86234. break;
  86235. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86236. returnValue = new this.BJSCANNON.Particle();
  86237. break;
  86238. }
  86239. return returnValue;
  86240. };
  86241. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  86242. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86243. var transform = object.computeWorldMatrix(true);
  86244. // convert rawVerts to object space
  86245. var temp = new Array();
  86246. var index;
  86247. for (index = 0; index < pos.length; index += 3) {
  86248. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  86249. }
  86250. pos = temp;
  86251. var matrix = new Array();
  86252. //For now pointDepth will not be used and will be automatically calculated.
  86253. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  86254. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  86255. var boundingInfo = object.getBoundingInfo();
  86256. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  86257. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  86258. var elementSize = dim * 2 / arraySize;
  86259. for (var i = 0; i < pos.length; i = i + 3) {
  86260. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  86261. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  86262. var y = -pos[i + 2] + minY;
  86263. if (!matrix[x]) {
  86264. matrix[x] = [];
  86265. }
  86266. if (!matrix[x][z]) {
  86267. matrix[x][z] = y;
  86268. }
  86269. matrix[x][z] = Math.max(y, matrix[x][z]);
  86270. }
  86271. for (var x = 0; x <= arraySize; ++x) {
  86272. if (!matrix[x]) {
  86273. var loc = 1;
  86274. while (!matrix[(x + loc) % arraySize]) {
  86275. loc++;
  86276. }
  86277. matrix[x] = matrix[(x + loc) % arraySize].slice();
  86278. //console.log("missing x", x);
  86279. }
  86280. for (var z = 0; z <= arraySize; ++z) {
  86281. if (!matrix[x][z]) {
  86282. var loc = 1;
  86283. var newValue;
  86284. while (newValue === undefined) {
  86285. newValue = matrix[x][(z + loc++) % arraySize];
  86286. }
  86287. matrix[x][z] = newValue;
  86288. }
  86289. }
  86290. }
  86291. var shape = new this.BJSCANNON.Heightfield(matrix, {
  86292. elementSize: elementSize
  86293. });
  86294. //For future reference, needed for body transformation
  86295. shape.minY = minY;
  86296. return shape;
  86297. };
  86298. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  86299. var object = impostor.object;
  86300. //make sure it is updated...
  86301. object.computeWorldMatrix && object.computeWorldMatrix(true);
  86302. // The delta between the mesh position and the mesh bounding box center
  86303. var bInfo = object.getBoundingInfo();
  86304. if (!bInfo)
  86305. return;
  86306. var center = impostor.getObjectCenter();
  86307. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  86308. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  86309. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  86310. this._tmpPosition.copyFrom(center);
  86311. var quaternion = object.rotationQuaternion;
  86312. if (!quaternion) {
  86313. return;
  86314. }
  86315. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  86316. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  86317. //-90 DEG in X, precalculated
  86318. quaternion = quaternion.multiply(this._minus90X);
  86319. //Invert! (Precalculated, 90 deg in X)
  86320. //No need to clone. this will never change.
  86321. impostor.setDeltaRotation(this._plus90X);
  86322. }
  86323. //If it is a heightfield, if should be centered.
  86324. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  86325. var mesh = object;
  86326. var boundingInfo = mesh.getBoundingInfo();
  86327. //calculate the correct body position:
  86328. var rotationQuaternion = mesh.rotationQuaternion;
  86329. mesh.rotationQuaternion = this._tmpUnityRotation;
  86330. mesh.computeWorldMatrix(true);
  86331. //get original center with no rotation
  86332. var c = center.clone();
  86333. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  86334. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  86335. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  86336. mesh.setPreTransformMatrix(p);
  86337. mesh.computeWorldMatrix(true);
  86338. //calculate the translation
  86339. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  86340. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  86341. //add it inverted to the delta
  86342. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  86343. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  86344. //rotation is back
  86345. mesh.rotationQuaternion = rotationQuaternion;
  86346. mesh.setPreTransformMatrix(oldPivot);
  86347. mesh.computeWorldMatrix(true);
  86348. }
  86349. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  86350. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  86351. //this._tmpPosition.copyFrom(object.position);
  86352. }
  86353. impostor.setDeltaPosition(this._tmpDeltaPosition);
  86354. //Now update the impostor object
  86355. impostor.physicsBody.position.copy(this._tmpPosition);
  86356. impostor.physicsBody.quaternion.copy(quaternion);
  86357. };
  86358. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86359. impostor.object.position.copyFrom(impostor.physicsBody.position);
  86360. if (impostor.object.rotationQuaternion) {
  86361. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  86362. }
  86363. };
  86364. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86365. impostor.physicsBody.position.copy(newPosition);
  86366. impostor.physicsBody.quaternion.copy(newRotation);
  86367. };
  86368. CannonJSPlugin.prototype.isSupported = function () {
  86369. return this.BJSCANNON !== undefined;
  86370. };
  86371. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86372. impostor.physicsBody.velocity.copy(velocity);
  86373. };
  86374. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86375. impostor.physicsBody.angularVelocity.copy(velocity);
  86376. };
  86377. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86378. var v = impostor.physicsBody.velocity;
  86379. if (!v) {
  86380. return null;
  86381. }
  86382. return new BABYLON.Vector3(v.x, v.y, v.z);
  86383. };
  86384. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86385. var v = impostor.physicsBody.angularVelocity;
  86386. if (!v) {
  86387. return null;
  86388. }
  86389. return new BABYLON.Vector3(v.x, v.y, v.z);
  86390. };
  86391. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86392. impostor.physicsBody.mass = mass;
  86393. impostor.physicsBody.updateMassProperties();
  86394. };
  86395. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  86396. return impostor.physicsBody.mass;
  86397. };
  86398. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  86399. return impostor.physicsBody.material.friction;
  86400. };
  86401. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86402. impostor.physicsBody.material.friction = friction;
  86403. };
  86404. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86405. return impostor.physicsBody.material.restitution;
  86406. };
  86407. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86408. impostor.physicsBody.material.restitution = restitution;
  86409. };
  86410. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  86411. impostor.physicsBody.sleep();
  86412. };
  86413. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  86414. impostor.physicsBody.wakeUp();
  86415. };
  86416. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86417. joint.physicsJoint.distance = maxDistance;
  86418. };
  86419. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86420. // if (!motorIndex) {
  86421. // joint.physicsJoint.enableMotor();
  86422. // }
  86423. // }
  86424. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86425. // if (!motorIndex) {
  86426. // joint.physicsJoint.disableMotor();
  86427. // }
  86428. // }
  86429. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86430. if (!motorIndex) {
  86431. joint.physicsJoint.enableMotor();
  86432. joint.physicsJoint.setMotorSpeed(speed);
  86433. if (maxForce) {
  86434. this.setLimit(joint, maxForce);
  86435. }
  86436. }
  86437. };
  86438. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  86439. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  86440. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  86441. };
  86442. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86443. var body = impostor.physicsBody;
  86444. mesh.position.x = body.position.x;
  86445. mesh.position.y = body.position.y;
  86446. mesh.position.z = body.position.z;
  86447. if (mesh.rotationQuaternion) {
  86448. mesh.rotationQuaternion.x = body.quaternion.x;
  86449. mesh.rotationQuaternion.y = body.quaternion.y;
  86450. mesh.rotationQuaternion.z = body.quaternion.z;
  86451. mesh.rotationQuaternion.w = body.quaternion.w;
  86452. }
  86453. };
  86454. CannonJSPlugin.prototype.getRadius = function (impostor) {
  86455. var shape = impostor.physicsBody.shapes[0];
  86456. return shape.boundingSphereRadius;
  86457. };
  86458. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86459. var shape = impostor.physicsBody.shapes[0];
  86460. result.x = shape.halfExtents.x * 2;
  86461. result.y = shape.halfExtents.y * 2;
  86462. result.z = shape.halfExtents.z * 2;
  86463. };
  86464. CannonJSPlugin.prototype.dispose = function () {
  86465. };
  86466. CannonJSPlugin.prototype._extendNamespace = function () {
  86467. //this will force cannon to execute at least one step when using interpolation
  86468. var step_tmp1 = new this.BJSCANNON.Vec3();
  86469. var Engine = this.BJSCANNON;
  86470. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  86471. maxSubSteps = maxSubSteps || 10;
  86472. timeSinceLastCalled = timeSinceLastCalled || 0;
  86473. if (timeSinceLastCalled === 0) {
  86474. this.internalStep(dt);
  86475. this.time += dt;
  86476. }
  86477. else {
  86478. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  86479. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  86480. var t0 = performance.now();
  86481. for (var i = 0; i !== internalSteps; i++) {
  86482. this.internalStep(dt);
  86483. if (performance.now() - t0 > dt * 1000) {
  86484. break;
  86485. }
  86486. }
  86487. this.time += timeSinceLastCalled;
  86488. var h = this.time % dt;
  86489. var h_div_dt = h / dt;
  86490. var interpvelo = step_tmp1;
  86491. var bodies = this.bodies;
  86492. for (var j = 0; j !== bodies.length; j++) {
  86493. var b = bodies[j];
  86494. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  86495. b.position.vsub(b.previousPosition, interpvelo);
  86496. interpvelo.scale(h_div_dt, interpvelo);
  86497. b.position.vadd(interpvelo, b.interpolatedPosition);
  86498. }
  86499. else {
  86500. b.interpolatedPosition.copy(b.position);
  86501. b.interpolatedQuaternion.copy(b.quaternion);
  86502. }
  86503. }
  86504. }
  86505. };
  86506. };
  86507. return CannonJSPlugin;
  86508. }());
  86509. BABYLON.CannonJSPlugin = CannonJSPlugin;
  86510. })(BABYLON || (BABYLON = {}));
  86511. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  86512. var BABYLON;
  86513. (function (BABYLON) {
  86514. var OimoJSPlugin = /** @class */ (function () {
  86515. function OimoJSPlugin(iterations) {
  86516. this.name = "OimoJSPlugin";
  86517. this._tmpImpostorsArray = [];
  86518. this._tmpPositionVector = BABYLON.Vector3.Zero();
  86519. this.BJSOIMO = OIMO;
  86520. this.world = new this.BJSOIMO.World({
  86521. iterations: iterations
  86522. });
  86523. this.world.clear();
  86524. }
  86525. OimoJSPlugin.prototype.setGravity = function (gravity) {
  86526. this.world.gravity.copy(gravity);
  86527. };
  86528. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  86529. this.world.timeStep = timeStep;
  86530. };
  86531. OimoJSPlugin.prototype.getTimeStep = function () {
  86532. return this.world.timeStep;
  86533. };
  86534. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  86535. var _this = this;
  86536. impostors.forEach(function (impostor) {
  86537. impostor.beforeStep();
  86538. });
  86539. this.world.step();
  86540. impostors.forEach(function (impostor) {
  86541. impostor.afterStep();
  86542. //update the ordered impostors array
  86543. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  86544. });
  86545. //check for collisions
  86546. var contact = this.world.contacts;
  86547. while (contact !== null) {
  86548. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  86549. contact = contact.next;
  86550. continue;
  86551. }
  86552. //is this body colliding with any other? get the impostor
  86553. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  86554. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  86555. if (!mainImpostor || !collidingImpostor) {
  86556. contact = contact.next;
  86557. continue;
  86558. }
  86559. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  86560. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  86561. contact = contact.next;
  86562. }
  86563. };
  86564. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86565. var mass = impostor.physicsBody.mass;
  86566. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  86567. };
  86568. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86569. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  86570. this.applyImpulse(impostor, force, contactPoint);
  86571. };
  86572. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86573. var _this = this;
  86574. //parent-child relationship. Does this impostor has a parent impostor?
  86575. if (impostor.parent) {
  86576. if (impostor.physicsBody) {
  86577. this.removePhysicsBody(impostor);
  86578. //TODO is that needed?
  86579. impostor.forceUpdate();
  86580. }
  86581. return;
  86582. }
  86583. if (impostor.isBodyInitRequired()) {
  86584. var bodyConfig = {
  86585. name: impostor.uniqueId,
  86586. //Oimo must have mass, also for static objects.
  86587. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  86588. size: [],
  86589. type: [],
  86590. pos: [],
  86591. posShape: [],
  86592. rot: [],
  86593. rotShape: [],
  86594. move: impostor.getParam("mass") !== 0,
  86595. density: impostor.getParam("mass"),
  86596. friction: impostor.getParam("friction"),
  86597. restitution: impostor.getParam("restitution"),
  86598. //Supporting older versions of Oimo
  86599. world: this.world
  86600. };
  86601. var impostors = [impostor];
  86602. var addToArray = function (parent) {
  86603. if (!parent.getChildMeshes)
  86604. return;
  86605. parent.getChildMeshes().forEach(function (m) {
  86606. if (m.physicsImpostor) {
  86607. impostors.push(m.physicsImpostor);
  86608. //m.physicsImpostor._init();
  86609. }
  86610. });
  86611. };
  86612. addToArray(impostor.object);
  86613. var checkWithEpsilon_1 = function (value) {
  86614. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  86615. };
  86616. impostors.forEach(function (i) {
  86617. if (!i.object.rotationQuaternion) {
  86618. return;
  86619. }
  86620. //get the correct bounding box
  86621. var oldQuaternion = i.object.rotationQuaternion;
  86622. var rot = oldQuaternion.toEulerAngles();
  86623. var extendSize = i.getObjectExtendSize();
  86624. var radToDeg = 57.295779513082320876;
  86625. if (i === impostor) {
  86626. var center = impostor.getObjectCenter();
  86627. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  86628. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  86629. //Can also use Array.prototype.push.apply
  86630. bodyConfig.pos.push(center.x);
  86631. bodyConfig.pos.push(center.y);
  86632. bodyConfig.pos.push(center.z);
  86633. bodyConfig.posShape.push(0, 0, 0);
  86634. //tmp solution
  86635. bodyConfig.rot.push(rot.x * radToDeg);
  86636. bodyConfig.rot.push(rot.y * radToDeg);
  86637. bodyConfig.rot.push(rot.z * radToDeg);
  86638. bodyConfig.rotShape.push(0, 0, 0);
  86639. }
  86640. else {
  86641. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  86642. bodyConfig.posShape.push(localPosition.x);
  86643. bodyConfig.posShape.push(localPosition.y);
  86644. bodyConfig.posShape.push(localPosition.z);
  86645. bodyConfig.pos.push(0, 0, 0);
  86646. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  86647. bodyConfig.rot.push(0);
  86648. bodyConfig.rot.push(0);
  86649. bodyConfig.rot.push(0);
  86650. bodyConfig.rotShape.push(rot.x * radToDeg);
  86651. bodyConfig.rotShape.push(rot.y * radToDeg);
  86652. bodyConfig.rotShape.push(rot.z * radToDeg);
  86653. }
  86654. // register mesh
  86655. switch (i.type) {
  86656. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86657. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  86658. case BABYLON.PhysicsImpostor.SphereImpostor:
  86659. var radiusX = extendSize.x;
  86660. var radiusY = extendSize.y;
  86661. var radiusZ = extendSize.z;
  86662. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  86663. bodyConfig.type.push('sphere');
  86664. //due to the way oimo works with compounds, add 3 times
  86665. bodyConfig.size.push(size);
  86666. bodyConfig.size.push(size);
  86667. bodyConfig.size.push(size);
  86668. break;
  86669. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86670. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  86671. var sizeY = checkWithEpsilon_1(extendSize.y);
  86672. bodyConfig.type.push('cylinder');
  86673. bodyConfig.size.push(sizeX);
  86674. bodyConfig.size.push(sizeY);
  86675. //due to the way oimo works with compounds, add one more value.
  86676. bodyConfig.size.push(sizeY);
  86677. break;
  86678. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86679. case BABYLON.PhysicsImpostor.BoxImpostor:
  86680. default:
  86681. var sizeX = checkWithEpsilon_1(extendSize.x);
  86682. var sizeY = checkWithEpsilon_1(extendSize.y);
  86683. var sizeZ = checkWithEpsilon_1(extendSize.z);
  86684. bodyConfig.type.push('box');
  86685. //if (i === impostor) {
  86686. bodyConfig.size.push(sizeX);
  86687. bodyConfig.size.push(sizeY);
  86688. bodyConfig.size.push(sizeZ);
  86689. //} else {
  86690. // bodyConfig.size.push(0,0,0);
  86691. //}
  86692. break;
  86693. }
  86694. //actually not needed, but hey...
  86695. i.object.rotationQuaternion = oldQuaternion;
  86696. });
  86697. impostor.physicsBody = this.world.add(bodyConfig);
  86698. }
  86699. else {
  86700. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  86701. }
  86702. impostor.setDeltaPosition(this._tmpPositionVector);
  86703. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  86704. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  86705. };
  86706. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86707. //impostor.physicsBody.dispose();
  86708. //Same as : (older oimo versions)
  86709. this.world.removeRigidBody(impostor.physicsBody);
  86710. };
  86711. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86712. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86713. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86714. if (!mainBody || !connectedBody) {
  86715. return;
  86716. }
  86717. var jointData = impostorJoint.joint.jointData;
  86718. var options = jointData.nativeParams || {};
  86719. var type;
  86720. var nativeJointData = {
  86721. body1: mainBody,
  86722. body2: connectedBody,
  86723. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  86724. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  86725. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  86726. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  86727. min: options.min,
  86728. max: options.max,
  86729. collision: options.collision || jointData.collision,
  86730. spring: options.spring,
  86731. //supporting older version of Oimo
  86732. world: this.world
  86733. };
  86734. switch (impostorJoint.joint.type) {
  86735. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86736. type = "jointBall";
  86737. break;
  86738. case BABYLON.PhysicsJoint.SpringJoint:
  86739. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  86740. var springData = jointData;
  86741. nativeJointData.min = springData.length || nativeJointData.min;
  86742. //Max should also be set, just make sure it is at least min
  86743. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  86744. case BABYLON.PhysicsJoint.DistanceJoint:
  86745. type = "jointDistance";
  86746. nativeJointData.max = jointData.maxDistance;
  86747. break;
  86748. case BABYLON.PhysicsJoint.PrismaticJoint:
  86749. type = "jointPrisme";
  86750. break;
  86751. case BABYLON.PhysicsJoint.SliderJoint:
  86752. type = "jointSlide";
  86753. break;
  86754. case BABYLON.PhysicsJoint.WheelJoint:
  86755. type = "jointWheel";
  86756. break;
  86757. case BABYLON.PhysicsJoint.HingeJoint:
  86758. default:
  86759. type = "jointHinge";
  86760. break;
  86761. }
  86762. nativeJointData.type = type;
  86763. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  86764. };
  86765. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86766. //Bug in Oimo prevents us from disposing a joint in the playground
  86767. //joint.joint.physicsJoint.dispose();
  86768. //So we will bruteforce it!
  86769. try {
  86770. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  86771. }
  86772. catch (e) {
  86773. BABYLON.Tools.Warn(e);
  86774. }
  86775. };
  86776. OimoJSPlugin.prototype.isSupported = function () {
  86777. return this.BJSOIMO !== undefined;
  86778. };
  86779. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86780. if (!impostor.physicsBody.sleeping) {
  86781. //TODO check that
  86782. /*if (impostor.physicsBody.shapes.next) {
  86783. var parentShape = this._getLastShape(impostor.physicsBody);
  86784. impostor.object.position.copyFrom(parentShape.position);
  86785. console.log(parentShape.position);
  86786. } else {*/
  86787. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  86788. //}
  86789. if (impostor.object.rotationQuaternion) {
  86790. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  86791. }
  86792. }
  86793. };
  86794. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86795. var body = impostor.physicsBody;
  86796. body.position.copy(newPosition);
  86797. body.orientation.copy(newRotation);
  86798. body.syncShapes();
  86799. body.awake();
  86800. };
  86801. /*private _getLastShape(body: any): any {
  86802. var lastShape = body.shapes;
  86803. while (lastShape.next) {
  86804. lastShape = lastShape.next;
  86805. }
  86806. return lastShape;
  86807. }*/
  86808. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86809. impostor.physicsBody.linearVelocity.copy(velocity);
  86810. };
  86811. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86812. impostor.physicsBody.angularVelocity.copy(velocity);
  86813. };
  86814. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86815. var v = impostor.physicsBody.linearVelocity;
  86816. if (!v) {
  86817. return null;
  86818. }
  86819. return new BABYLON.Vector3(v.x, v.y, v.z);
  86820. };
  86821. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86822. var v = impostor.physicsBody.angularVelocity;
  86823. if (!v) {
  86824. return null;
  86825. }
  86826. return new BABYLON.Vector3(v.x, v.y, v.z);
  86827. };
  86828. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86829. var staticBody = mass === 0;
  86830. //this will actually set the body's density and not its mass.
  86831. //But this is how oimo treats the mass variable.
  86832. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  86833. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  86834. };
  86835. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  86836. return impostor.physicsBody.shapes.density;
  86837. };
  86838. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  86839. return impostor.physicsBody.shapes.friction;
  86840. };
  86841. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86842. impostor.physicsBody.shapes.friction = friction;
  86843. };
  86844. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86845. return impostor.physicsBody.shapes.restitution;
  86846. };
  86847. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86848. impostor.physicsBody.shapes.restitution = restitution;
  86849. };
  86850. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  86851. impostor.physicsBody.sleep();
  86852. };
  86853. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  86854. impostor.physicsBody.awake();
  86855. };
  86856. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86857. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  86858. if (minDistance !== void 0) {
  86859. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  86860. }
  86861. };
  86862. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86863. //TODO separate rotational and transational motors.
  86864. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86865. if (motor) {
  86866. motor.setMotor(speed, maxForce);
  86867. }
  86868. };
  86869. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  86870. //TODO separate rotational and transational motors.
  86871. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86872. if (motor) {
  86873. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  86874. }
  86875. };
  86876. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86877. var body = impostor.physicsBody;
  86878. mesh.position.x = body.position.x;
  86879. mesh.position.y = body.position.y;
  86880. mesh.position.z = body.position.z;
  86881. if (mesh.rotationQuaternion) {
  86882. mesh.rotationQuaternion.x = body.orientation.x;
  86883. mesh.rotationQuaternion.y = body.orientation.y;
  86884. mesh.rotationQuaternion.z = body.orientation.z;
  86885. mesh.rotationQuaternion.w = body.orientation.s;
  86886. }
  86887. };
  86888. OimoJSPlugin.prototype.getRadius = function (impostor) {
  86889. return impostor.physicsBody.shapes.radius;
  86890. };
  86891. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86892. var shape = impostor.physicsBody.shapes;
  86893. result.x = shape.halfWidth * 2;
  86894. result.y = shape.halfHeight * 2;
  86895. result.z = shape.halfDepth * 2;
  86896. };
  86897. OimoJSPlugin.prototype.dispose = function () {
  86898. this.world.clear();
  86899. };
  86900. return OimoJSPlugin;
  86901. }());
  86902. BABYLON.OimoJSPlugin = OimoJSPlugin;
  86903. })(BABYLON || (BABYLON = {}));
  86904. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  86905. var BABYLON;
  86906. (function (BABYLON) {
  86907. /*
  86908. * Based on jsTGALoader - Javascript loader for TGA file
  86909. * By Vincent Thibault
  86910. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  86911. */
  86912. var TGATools = /** @class */ (function () {
  86913. function TGATools() {
  86914. }
  86915. TGATools.GetTGAHeader = function (data) {
  86916. var offset = 0;
  86917. var header = {
  86918. id_length: data[offset++],
  86919. colormap_type: data[offset++],
  86920. image_type: data[offset++],
  86921. colormap_index: data[offset++] | data[offset++] << 8,
  86922. colormap_length: data[offset++] | data[offset++] << 8,
  86923. colormap_size: data[offset++],
  86924. origin: [
  86925. data[offset++] | data[offset++] << 8,
  86926. data[offset++] | data[offset++] << 8
  86927. ],
  86928. width: data[offset++] | data[offset++] << 8,
  86929. height: data[offset++] | data[offset++] << 8,
  86930. pixel_size: data[offset++],
  86931. flags: data[offset++]
  86932. };
  86933. return header;
  86934. };
  86935. /**
  86936. * Uploads TGA content to a Babylon Texture
  86937. * @hidden
  86938. */
  86939. TGATools.UploadContent = function (texture, data) {
  86940. // Not enough data to contain header ?
  86941. if (data.length < 19) {
  86942. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  86943. return;
  86944. }
  86945. // Read Header
  86946. var offset = 18;
  86947. var header = TGATools.GetTGAHeader(data);
  86948. // Assume it's a valid Targa file.
  86949. if (header.id_length + offset > data.length) {
  86950. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  86951. return;
  86952. }
  86953. // Skip not needed data
  86954. offset += header.id_length;
  86955. var use_rle = false;
  86956. var use_pal = false;
  86957. var use_grey = false;
  86958. // Get some informations.
  86959. switch (header.image_type) {
  86960. case TGATools._TYPE_RLE_INDEXED:
  86961. use_rle = true;
  86962. case TGATools._TYPE_INDEXED:
  86963. use_pal = true;
  86964. break;
  86965. case TGATools._TYPE_RLE_RGB:
  86966. use_rle = true;
  86967. case TGATools._TYPE_RGB:
  86968. // use_rgb = true;
  86969. break;
  86970. case TGATools._TYPE_RLE_GREY:
  86971. use_rle = true;
  86972. case TGATools._TYPE_GREY:
  86973. use_grey = true;
  86974. break;
  86975. }
  86976. var pixel_data;
  86977. // var numAlphaBits = header.flags & 0xf;
  86978. var pixel_size = header.pixel_size >> 3;
  86979. var pixel_total = header.width * header.height * pixel_size;
  86980. // Read palettes
  86981. var palettes;
  86982. if (use_pal) {
  86983. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  86984. }
  86985. // Read LRE
  86986. if (use_rle) {
  86987. pixel_data = new Uint8Array(pixel_total);
  86988. var c, count, i;
  86989. var localOffset = 0;
  86990. var pixels = new Uint8Array(pixel_size);
  86991. while (offset < pixel_total && localOffset < pixel_total) {
  86992. c = data[offset++];
  86993. count = (c & 0x7f) + 1;
  86994. // RLE pixels
  86995. if (c & 0x80) {
  86996. // Bind pixel tmp array
  86997. for (i = 0; i < pixel_size; ++i) {
  86998. pixels[i] = data[offset++];
  86999. }
  87000. // Copy pixel array
  87001. for (i = 0; i < count; ++i) {
  87002. pixel_data.set(pixels, localOffset + i * pixel_size);
  87003. }
  87004. localOffset += pixel_size * count;
  87005. }
  87006. // Raw pixels
  87007. else {
  87008. count *= pixel_size;
  87009. for (i = 0; i < count; ++i) {
  87010. pixel_data[localOffset + i] = data[offset++];
  87011. }
  87012. localOffset += count;
  87013. }
  87014. }
  87015. }
  87016. // RAW Pixels
  87017. else {
  87018. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  87019. }
  87020. // Load to texture
  87021. var x_start, y_start, x_step, y_step, y_end, x_end;
  87022. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  87023. default:
  87024. case TGATools._ORIGIN_UL:
  87025. x_start = 0;
  87026. x_step = 1;
  87027. x_end = header.width;
  87028. y_start = 0;
  87029. y_step = 1;
  87030. y_end = header.height;
  87031. break;
  87032. case TGATools._ORIGIN_BL:
  87033. x_start = 0;
  87034. x_step = 1;
  87035. x_end = header.width;
  87036. y_start = header.height - 1;
  87037. y_step = -1;
  87038. y_end = -1;
  87039. break;
  87040. case TGATools._ORIGIN_UR:
  87041. x_start = header.width - 1;
  87042. x_step = -1;
  87043. x_end = -1;
  87044. y_start = 0;
  87045. y_step = 1;
  87046. y_end = header.height;
  87047. break;
  87048. case TGATools._ORIGIN_BR:
  87049. x_start = header.width - 1;
  87050. x_step = -1;
  87051. x_end = -1;
  87052. y_start = header.height - 1;
  87053. y_step = -1;
  87054. y_end = -1;
  87055. break;
  87056. }
  87057. // Load the specify method
  87058. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  87059. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  87060. var engine = texture.getEngine();
  87061. engine._uploadArrayBufferViewToTexture(texture, imageData);
  87062. };
  87063. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87064. var image = pixel_data, colormap = palettes;
  87065. var width = header.width, height = header.height;
  87066. var color, i = 0, x, y;
  87067. var imageData = new Uint8Array(width * height * 4);
  87068. for (y = y_start; y !== y_end; y += y_step) {
  87069. for (x = x_start; x !== x_end; x += x_step, i++) {
  87070. color = image[i];
  87071. imageData[(x + width * y) * 4 + 3] = 255;
  87072. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  87073. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  87074. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  87075. }
  87076. }
  87077. return imageData;
  87078. };
  87079. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87080. var image = pixel_data;
  87081. var width = header.width, height = header.height;
  87082. var color, i = 0, x, y;
  87083. var imageData = new Uint8Array(width * height * 4);
  87084. for (y = y_start; y !== y_end; y += y_step) {
  87085. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  87086. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  87087. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  87088. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  87089. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  87090. imageData[(x + width * y) * 4 + 0] = r;
  87091. imageData[(x + width * y) * 4 + 1] = g;
  87092. imageData[(x + width * y) * 4 + 2] = b;
  87093. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  87094. }
  87095. }
  87096. return imageData;
  87097. };
  87098. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87099. var image = pixel_data;
  87100. var width = header.width, height = header.height;
  87101. var i = 0, x, y;
  87102. var imageData = new Uint8Array(width * height * 4);
  87103. for (y = y_start; y !== y_end; y += y_step) {
  87104. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  87105. imageData[(x + width * y) * 4 + 3] = 255;
  87106. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87107. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  87108. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  87109. }
  87110. }
  87111. return imageData;
  87112. };
  87113. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87114. var image = pixel_data;
  87115. var width = header.width, height = header.height;
  87116. var i = 0, x, y;
  87117. var imageData = new Uint8Array(width * height * 4);
  87118. for (y = y_start; y !== y_end; y += y_step) {
  87119. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  87120. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87121. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  87122. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  87123. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  87124. }
  87125. }
  87126. return imageData;
  87127. };
  87128. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87129. var image = pixel_data;
  87130. var width = header.width, height = header.height;
  87131. var color, i = 0, x, y;
  87132. var imageData = new Uint8Array(width * height * 4);
  87133. for (y = y_start; y !== y_end; y += y_step) {
  87134. for (x = x_start; x !== x_end; x += x_step, i++) {
  87135. color = image[i];
  87136. imageData[(x + width * y) * 4 + 0] = color;
  87137. imageData[(x + width * y) * 4 + 1] = color;
  87138. imageData[(x + width * y) * 4 + 2] = color;
  87139. imageData[(x + width * y) * 4 + 3] = 255;
  87140. }
  87141. }
  87142. return imageData;
  87143. };
  87144. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87145. var image = pixel_data;
  87146. var width = header.width, height = header.height;
  87147. var i = 0, x, y;
  87148. var imageData = new Uint8Array(width * height * 4);
  87149. for (y = y_start; y !== y_end; y += y_step) {
  87150. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  87151. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  87152. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  87153. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87154. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  87155. }
  87156. }
  87157. return imageData;
  87158. };
  87159. //private static _TYPE_NO_DATA = 0;
  87160. TGATools._TYPE_INDEXED = 1;
  87161. TGATools._TYPE_RGB = 2;
  87162. TGATools._TYPE_GREY = 3;
  87163. TGATools._TYPE_RLE_INDEXED = 9;
  87164. TGATools._TYPE_RLE_RGB = 10;
  87165. TGATools._TYPE_RLE_GREY = 11;
  87166. TGATools._ORIGIN_MASK = 0x30;
  87167. TGATools._ORIGIN_SHIFT = 0x04;
  87168. TGATools._ORIGIN_BL = 0x00;
  87169. TGATools._ORIGIN_BR = 0x01;
  87170. TGATools._ORIGIN_UL = 0x02;
  87171. TGATools._ORIGIN_UR = 0x03;
  87172. return TGATools;
  87173. }());
  87174. BABYLON.TGATools = TGATools;
  87175. })(BABYLON || (BABYLON = {}));
  87176. //# sourceMappingURL=babylon.tga.js.map
  87177. var BABYLON;
  87178. (function (BABYLON) {
  87179. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  87180. // All values and structures referenced from:
  87181. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  87182. var DDS_MAGIC = 0x20534444;
  87183. var
  87184. //DDSD_CAPS = 0x1,
  87185. //DDSD_HEIGHT = 0x2,
  87186. //DDSD_WIDTH = 0x4,
  87187. //DDSD_PITCH = 0x8,
  87188. //DDSD_PIXELFORMAT = 0x1000,
  87189. DDSD_MIPMAPCOUNT = 0x20000;
  87190. //DDSD_LINEARSIZE = 0x80000,
  87191. //DDSD_DEPTH = 0x800000;
  87192. // var DDSCAPS_COMPLEX = 0x8,
  87193. // DDSCAPS_MIPMAP = 0x400000,
  87194. // DDSCAPS_TEXTURE = 0x1000;
  87195. var DDSCAPS2_CUBEMAP = 0x200;
  87196. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  87197. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  87198. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  87199. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  87200. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  87201. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  87202. // DDSCAPS2_VOLUME = 0x200000;
  87203. var
  87204. //DDPF_ALPHAPIXELS = 0x1,
  87205. //DDPF_ALPHA = 0x2,
  87206. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  87207. //DDPF_YUV = 0x200,
  87208. DDPF_LUMINANCE = 0x20000;
  87209. function FourCCToInt32(value) {
  87210. return value.charCodeAt(0) +
  87211. (value.charCodeAt(1) << 8) +
  87212. (value.charCodeAt(2) << 16) +
  87213. (value.charCodeAt(3) << 24);
  87214. }
  87215. function Int32ToFourCC(value) {
  87216. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  87217. }
  87218. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  87219. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  87220. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  87221. var FOURCC_DX10 = FourCCToInt32("DX10");
  87222. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  87223. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  87224. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  87225. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  87226. var headerLengthInt = 31; // The header length in 32 bit ints
  87227. // Offsets into the header array
  87228. var off_magic = 0;
  87229. var off_size = 1;
  87230. var off_flags = 2;
  87231. var off_height = 3;
  87232. var off_width = 4;
  87233. var off_mipmapCount = 7;
  87234. var off_pfFlags = 20;
  87235. var off_pfFourCC = 21;
  87236. var off_RGBbpp = 22;
  87237. var off_RMask = 23;
  87238. var off_GMask = 24;
  87239. var off_BMask = 25;
  87240. var off_AMask = 26;
  87241. // var off_caps1 = 27;
  87242. var off_caps2 = 28;
  87243. // var off_caps3 = 29;
  87244. // var off_caps4 = 30;
  87245. var off_dxgiFormat = 32;
  87246. ;
  87247. var DDSTools = /** @class */ (function () {
  87248. function DDSTools() {
  87249. }
  87250. DDSTools.GetDDSInfo = function (arrayBuffer) {
  87251. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87252. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  87253. var mipmapCount = 1;
  87254. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  87255. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87256. }
  87257. var fourCC = header[off_pfFourCC];
  87258. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  87259. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87260. switch (fourCC) {
  87261. case FOURCC_D3DFMT_R16G16B16A16F:
  87262. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87263. break;
  87264. case FOURCC_D3DFMT_R32G32B32A32F:
  87265. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87266. break;
  87267. case FOURCC_DX10:
  87268. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  87269. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87270. break;
  87271. }
  87272. }
  87273. return {
  87274. width: header[off_width],
  87275. height: header[off_height],
  87276. mipmapCount: mipmapCount,
  87277. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  87278. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  87279. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  87280. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  87281. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  87282. dxgiFormat: dxgiFormat,
  87283. textureType: textureType
  87284. };
  87285. };
  87286. DDSTools._ToHalfFloat = function (value) {
  87287. if (!DDSTools._FloatView) {
  87288. DDSTools._FloatView = new Float32Array(1);
  87289. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  87290. }
  87291. DDSTools._FloatView[0] = value;
  87292. var x = DDSTools._Int32View[0];
  87293. var bits = (x >> 16) & 0x8000; /* Get the sign */
  87294. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  87295. var e = (x >> 23) & 0xff; /* Using int is faster here */
  87296. /* If zero, or denormal, or exponent underflows too much for a denormal
  87297. * half, return signed zero. */
  87298. if (e < 103) {
  87299. return bits;
  87300. }
  87301. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  87302. if (e > 142) {
  87303. bits |= 0x7c00;
  87304. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  87305. * not Inf, so make sure we set one mantissa bit too. */
  87306. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  87307. return bits;
  87308. }
  87309. /* If exponent underflows but not too much, return a denormal */
  87310. if (e < 113) {
  87311. m |= 0x0800;
  87312. /* Extra rounding may overflow and set mantissa to 0 and exponent
  87313. * to 1, which is OK. */
  87314. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  87315. return bits;
  87316. }
  87317. bits |= ((e - 112) << 10) | (m >> 1);
  87318. bits += m & 1;
  87319. return bits;
  87320. };
  87321. DDSTools._FromHalfFloat = function (value) {
  87322. var s = (value & 0x8000) >> 15;
  87323. var e = (value & 0x7C00) >> 10;
  87324. var f = value & 0x03FF;
  87325. if (e === 0) {
  87326. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  87327. }
  87328. else if (e == 0x1F) {
  87329. return f ? NaN : ((s ? -1 : 1) * Infinity);
  87330. }
  87331. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  87332. };
  87333. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87334. var destArray = new Float32Array(dataLength);
  87335. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87336. var index = 0;
  87337. for (var y = 0; y < height; y++) {
  87338. for (var x = 0; x < width; x++) {
  87339. var srcPos = (x + y * width) * 4;
  87340. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  87341. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  87342. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  87343. if (DDSTools.StoreLODInAlphaChannel) {
  87344. destArray[index + 3] = lod;
  87345. }
  87346. else {
  87347. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  87348. }
  87349. index += 4;
  87350. }
  87351. }
  87352. return destArray;
  87353. };
  87354. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87355. if (DDSTools.StoreLODInAlphaChannel) {
  87356. var destArray = new Uint16Array(dataLength);
  87357. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87358. var index = 0;
  87359. for (var y = 0; y < height; y++) {
  87360. for (var x = 0; x < width; x++) {
  87361. var srcPos = (x + y * width) * 4;
  87362. destArray[index] = srcData[srcPos];
  87363. destArray[index + 1] = srcData[srcPos + 1];
  87364. destArray[index + 2] = srcData[srcPos + 2];
  87365. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  87366. index += 4;
  87367. }
  87368. }
  87369. return destArray;
  87370. }
  87371. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  87372. };
  87373. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87374. if (DDSTools.StoreLODInAlphaChannel) {
  87375. var destArray = new Float32Array(dataLength);
  87376. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87377. var index = 0;
  87378. for (var y = 0; y < height; y++) {
  87379. for (var x = 0; x < width; x++) {
  87380. var srcPos = (x + y * width) * 4;
  87381. destArray[index] = srcData[srcPos];
  87382. destArray[index + 1] = srcData[srcPos + 1];
  87383. destArray[index + 2] = srcData[srcPos + 2];
  87384. destArray[index + 3] = lod;
  87385. index += 4;
  87386. }
  87387. }
  87388. return destArray;
  87389. }
  87390. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  87391. };
  87392. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87393. var destArray = new Uint8Array(dataLength);
  87394. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87395. var index = 0;
  87396. for (var y = 0; y < height; y++) {
  87397. for (var x = 0; x < width; x++) {
  87398. var srcPos = (x + y * width) * 4;
  87399. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  87400. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  87401. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  87402. if (DDSTools.StoreLODInAlphaChannel) {
  87403. destArray[index + 3] = lod;
  87404. }
  87405. else {
  87406. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  87407. }
  87408. index += 4;
  87409. }
  87410. }
  87411. return destArray;
  87412. };
  87413. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87414. var destArray = new Uint8Array(dataLength);
  87415. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87416. var index = 0;
  87417. for (var y = 0; y < height; y++) {
  87418. for (var x = 0; x < width; x++) {
  87419. var srcPos = (x + y * width) * 4;
  87420. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  87421. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  87422. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  87423. if (DDSTools.StoreLODInAlphaChannel) {
  87424. destArray[index + 3] = lod;
  87425. }
  87426. else {
  87427. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  87428. }
  87429. index += 4;
  87430. }
  87431. }
  87432. return destArray;
  87433. };
  87434. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  87435. var byteArray = new Uint8Array(dataLength);
  87436. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87437. var index = 0;
  87438. for (var y = 0; y < height; y++) {
  87439. for (var x = 0; x < width; x++) {
  87440. var srcPos = (x + y * width) * 4;
  87441. byteArray[index] = srcData[srcPos + rOffset];
  87442. byteArray[index + 1] = srcData[srcPos + gOffset];
  87443. byteArray[index + 2] = srcData[srcPos + bOffset];
  87444. byteArray[index + 3] = srcData[srcPos + aOffset];
  87445. index += 4;
  87446. }
  87447. }
  87448. return byteArray;
  87449. };
  87450. DDSTools._ExtractLongWordOrder = function (value) {
  87451. if (value === 0 || value === 255 || value === -16777216) {
  87452. return 0;
  87453. }
  87454. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  87455. };
  87456. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  87457. var byteArray = new Uint8Array(dataLength);
  87458. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87459. var index = 0;
  87460. for (var y = 0; y < height; y++) {
  87461. for (var x = 0; x < width; x++) {
  87462. var srcPos = (x + y * width) * 3;
  87463. byteArray[index] = srcData[srcPos + rOffset];
  87464. byteArray[index + 1] = srcData[srcPos + gOffset];
  87465. byteArray[index + 2] = srcData[srcPos + bOffset];
  87466. index += 3;
  87467. }
  87468. }
  87469. return byteArray;
  87470. };
  87471. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  87472. var byteArray = new Uint8Array(dataLength);
  87473. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87474. var index = 0;
  87475. for (var y = 0; y < height; y++) {
  87476. for (var x = 0; x < width; x++) {
  87477. var srcPos = (x + y * width);
  87478. byteArray[index] = srcData[srcPos];
  87479. index++;
  87480. }
  87481. }
  87482. return byteArray;
  87483. };
  87484. /**
  87485. * Uploads DDS Levels to a Babylon Texture
  87486. * @hidden
  87487. */
  87488. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  87489. if (lodIndex === void 0) { lodIndex = -1; }
  87490. var sphericalPolynomialFaces = null;
  87491. if (info.sphericalPolynomial) {
  87492. sphericalPolynomialFaces = new Array();
  87493. }
  87494. var ext = engine.getCaps().s3tc;
  87495. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87496. var fourCC, width, height, dataLength = 0, dataOffset;
  87497. var byteArray, mipmapCount, mip;
  87498. var internalCompressedFormat = 0;
  87499. var blockBytes = 1;
  87500. if (header[off_magic] !== DDS_MAGIC) {
  87501. BABYLON.Tools.Error("Invalid magic number in DDS header");
  87502. return;
  87503. }
  87504. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  87505. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  87506. return;
  87507. }
  87508. if (info.isCompressed && !ext) {
  87509. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  87510. return;
  87511. }
  87512. var bpp = header[off_RGBbpp];
  87513. dataOffset = header[off_size] + 4;
  87514. var computeFormats = false;
  87515. if (info.isFourCC) {
  87516. fourCC = header[off_pfFourCC];
  87517. switch (fourCC) {
  87518. case FOURCC_DXT1:
  87519. blockBytes = 8;
  87520. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  87521. break;
  87522. case FOURCC_DXT3:
  87523. blockBytes = 16;
  87524. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  87525. break;
  87526. case FOURCC_DXT5:
  87527. blockBytes = 16;
  87528. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  87529. break;
  87530. case FOURCC_D3DFMT_R16G16B16A16F:
  87531. computeFormats = true;
  87532. break;
  87533. case FOURCC_D3DFMT_R32G32B32A32F:
  87534. computeFormats = true;
  87535. break;
  87536. case FOURCC_DX10:
  87537. // There is an additionnal header so dataOffset need to be changed
  87538. dataOffset += 5 * 4; // 5 uints
  87539. var supported = false;
  87540. switch (info.dxgiFormat) {
  87541. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  87542. computeFormats = true;
  87543. supported = true;
  87544. break;
  87545. case DXGI_FORMAT_B8G8R8X8_UNORM:
  87546. info.isRGB = true;
  87547. info.isFourCC = false;
  87548. bpp = 32;
  87549. supported = true;
  87550. break;
  87551. }
  87552. if (supported) {
  87553. break;
  87554. }
  87555. default:
  87556. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  87557. return;
  87558. }
  87559. }
  87560. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  87561. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  87562. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  87563. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  87564. if (computeFormats) {
  87565. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87566. }
  87567. mipmapCount = 1;
  87568. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  87569. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87570. }
  87571. for (var face = 0; face < faces; face++) {
  87572. width = header[off_width];
  87573. height = header[off_height];
  87574. for (mip = 0; mip < mipmapCount; ++mip) {
  87575. if (lodIndex === -1 || lodIndex === mip) {
  87576. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  87577. var i = (lodIndex === -1) ? mip : 0;
  87578. if (!info.isCompressed && info.isFourCC) {
  87579. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  87580. dataLength = width * height * 4;
  87581. var floatArray = null;
  87582. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  87583. if (bpp === 128) {
  87584. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87585. if (sphericalPolynomialFaces && i == 0) {
  87586. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87587. }
  87588. }
  87589. else if (bpp === 64) {
  87590. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87591. if (sphericalPolynomialFaces && i == 0) {
  87592. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87593. }
  87594. }
  87595. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87596. }
  87597. else {
  87598. if (bpp === 128) {
  87599. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87600. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87601. if (sphericalPolynomialFaces && i == 0) {
  87602. sphericalPolynomialFaces.push(floatArray);
  87603. }
  87604. }
  87605. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  87606. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87607. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87608. if (sphericalPolynomialFaces && i == 0) {
  87609. sphericalPolynomialFaces.push(floatArray);
  87610. }
  87611. }
  87612. else { // 64
  87613. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87614. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87615. if (sphericalPolynomialFaces && i == 0) {
  87616. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87617. }
  87618. }
  87619. }
  87620. if (floatArray) {
  87621. engine._uploadDataToTextureDirectly(texture, width, height, floatArray, face, i);
  87622. }
  87623. }
  87624. else if (info.isRGB) {
  87625. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87626. if (bpp === 24) {
  87627. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  87628. dataLength = width * height * 3;
  87629. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  87630. engine._uploadDataToTextureDirectly(texture, width, height, byteArray, face, i);
  87631. }
  87632. else { // 32
  87633. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  87634. dataLength = width * height * 4;
  87635. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  87636. engine._uploadDataToTextureDirectly(texture, width, height, byteArray, face, i);
  87637. }
  87638. }
  87639. else if (info.isLuminance) {
  87640. var unpackAlignment = engine._getUnpackAlignement();
  87641. var unpaddedRowSize = width;
  87642. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  87643. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  87644. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  87645. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  87646. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87647. engine._uploadDataToTextureDirectly(texture, width, height, byteArray, face, i);
  87648. }
  87649. else {
  87650. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  87651. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  87652. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87653. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  87654. }
  87655. }
  87656. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  87657. width *= 0.5;
  87658. height *= 0.5;
  87659. width = Math.max(1.0, width);
  87660. height = Math.max(1.0, height);
  87661. }
  87662. if (currentFace !== undefined) {
  87663. // Loading a single face
  87664. break;
  87665. }
  87666. }
  87667. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  87668. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  87669. size: header[off_width],
  87670. right: sphericalPolynomialFaces[0],
  87671. left: sphericalPolynomialFaces[1],
  87672. up: sphericalPolynomialFaces[2],
  87673. down: sphericalPolynomialFaces[3],
  87674. front: sphericalPolynomialFaces[4],
  87675. back: sphericalPolynomialFaces[5],
  87676. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  87677. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87678. gammaSpace: false,
  87679. });
  87680. }
  87681. else {
  87682. info.sphericalPolynomial = undefined;
  87683. }
  87684. };
  87685. DDSTools.StoreLODInAlphaChannel = false;
  87686. return DDSTools;
  87687. }());
  87688. BABYLON.DDSTools = DDSTools;
  87689. })(BABYLON || (BABYLON = {}));
  87690. //# sourceMappingURL=babylon.dds.js.map
  87691. var BABYLON;
  87692. (function (BABYLON) {
  87693. /**
  87694. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  87695. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  87696. */
  87697. var KhronosTextureContainer = /** @class */ (function () {
  87698. /**
  87699. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  87700. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  87701. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  87702. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  87703. */
  87704. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  87705. this.arrayBuffer = arrayBuffer;
  87706. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  87707. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  87708. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  87709. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  87710. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  87711. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  87712. BABYLON.Tools.Error("texture missing KTX identifier");
  87713. return;
  87714. }
  87715. // load the reset of the header in native 32 bit int
  87716. var header = new Int32Array(this.arrayBuffer, 12, 13);
  87717. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  87718. var oppositeEndianess = header[0] === 0x01020304;
  87719. // read all the header elements in order they exist in the file, without modification (sans endainness)
  87720. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  87721. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  87722. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  87723. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  87724. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  87725. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  87726. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  87727. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  87728. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  87729. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  87730. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  87731. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  87732. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  87733. if (this.glType !== 0) {
  87734. BABYLON.Tools.Error("only compressed formats currently supported");
  87735. return;
  87736. }
  87737. else {
  87738. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  87739. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  87740. }
  87741. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  87742. BABYLON.Tools.Error("only 2D textures currently supported");
  87743. return;
  87744. }
  87745. if (this.numberOfArrayElements !== 0) {
  87746. BABYLON.Tools.Error("texture arrays not currently supported");
  87747. return;
  87748. }
  87749. if (this.numberOfFaces !== facesExpected) {
  87750. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  87751. return;
  87752. }
  87753. // we now have a completely validated file, so could use existence of loadType as success
  87754. // would need to make this more elaborate & adjust checks above to support more than one load type
  87755. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  87756. }
  87757. // not as fast hardware based, but will probably never need to use
  87758. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  87759. return ((val & 0xFF) << 24)
  87760. | ((val & 0xFF00) << 8)
  87761. | ((val >> 8) & 0xFF00)
  87762. | ((val >> 24) & 0xFF);
  87763. };
  87764. /**
  87765. * Uploads KTX content to a Babylon Texture.
  87766. * It is assumed that the texture has already been created & is currently bound
  87767. * @hidden
  87768. */
  87769. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  87770. switch (this.loadType) {
  87771. case KhronosTextureContainer.COMPRESSED_2D:
  87772. this._upload2DCompressedLevels(texture, loadMipmaps);
  87773. break;
  87774. case KhronosTextureContainer.TEX_2D:
  87775. case KhronosTextureContainer.COMPRESSED_3D:
  87776. case KhronosTextureContainer.TEX_3D:
  87777. }
  87778. };
  87779. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  87780. // initialize width & height for level 1
  87781. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  87782. var width = this.pixelWidth;
  87783. var height = this.pixelHeight;
  87784. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  87785. for (var level = 0; level < mipmapCount; level++) {
  87786. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  87787. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  87788. for (var face = 0; face < this.numberOfFaces; face++) {
  87789. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  87790. var engine = texture.getEngine();
  87791. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  87792. dataOffset += imageSize; // add size of the image for the next face/mipmap
  87793. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  87794. }
  87795. width = Math.max(1.0, width * 0.5);
  87796. height = Math.max(1.0, height * 0.5);
  87797. }
  87798. };
  87799. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  87800. // load types
  87801. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  87802. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  87803. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  87804. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  87805. return KhronosTextureContainer;
  87806. }());
  87807. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  87808. })(BABYLON || (BABYLON = {}));
  87809. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  87810. var BABYLON;
  87811. (function (BABYLON) {
  87812. var Debug;
  87813. (function (Debug) {
  87814. /**
  87815. * Class used to render a debug view of a given skeleton
  87816. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  87817. */
  87818. var SkeletonViewer = /** @class */ (function () {
  87819. /**
  87820. * Creates a new SkeletonViewer
  87821. * @param skeleton defines the skeleton to render
  87822. * @param mesh defines the mesh attached to the skeleton
  87823. * @param scene defines the hosting scene
  87824. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  87825. * @param renderingGroupId defines the rendering group id to use with the viewer
  87826. */
  87827. function SkeletonViewer(
  87828. /** defines the skeleton to render */
  87829. skeleton,
  87830. /** defines the mesh attached to the skeleton */
  87831. mesh, scene,
  87832. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  87833. autoUpdateBonesMatrices,
  87834. /** defines the rendering group id to use with the viewer */
  87835. renderingGroupId) {
  87836. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  87837. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  87838. this.skeleton = skeleton;
  87839. this.mesh = mesh;
  87840. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  87841. this.renderingGroupId = renderingGroupId;
  87842. /** Gets or sets the color used to render the skeleton */
  87843. this.color = BABYLON.Color3.White();
  87844. this._debugLines = new Array();
  87845. this._isEnabled = false;
  87846. this._scene = scene;
  87847. this.update();
  87848. this._renderFunction = this.update.bind(this);
  87849. }
  87850. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  87851. get: function () {
  87852. return this._isEnabled;
  87853. },
  87854. /** Gets or sets a boolean indicating if the viewer is enabled */
  87855. set: function (value) {
  87856. if (this._isEnabled === value) {
  87857. return;
  87858. }
  87859. this._isEnabled = value;
  87860. if (value) {
  87861. this._scene.registerBeforeRender(this._renderFunction);
  87862. }
  87863. else {
  87864. this._scene.unregisterBeforeRender(this._renderFunction);
  87865. }
  87866. },
  87867. enumerable: true,
  87868. configurable: true
  87869. });
  87870. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  87871. if (x === void 0) { x = 0; }
  87872. if (y === void 0) { y = 0; }
  87873. if (z === void 0) { z = 0; }
  87874. var tmat = BABYLON.Tmp.Matrix[0];
  87875. var parentBone = bone.getParent();
  87876. tmat.copyFrom(bone.getLocalMatrix());
  87877. if (x !== 0 || y !== 0 || z !== 0) {
  87878. var tmat2 = BABYLON.Tmp.Matrix[1];
  87879. BABYLON.Matrix.IdentityToRef(tmat2);
  87880. tmat2.m[12] = x;
  87881. tmat2.m[13] = y;
  87882. tmat2.m[14] = z;
  87883. tmat2.multiplyToRef(tmat, tmat);
  87884. }
  87885. if (parentBone) {
  87886. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  87887. }
  87888. tmat.multiplyToRef(meshMat, tmat);
  87889. position.x = tmat.m[12];
  87890. position.y = tmat.m[13];
  87891. position.z = tmat.m[14];
  87892. };
  87893. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  87894. var len = bones.length;
  87895. var meshPos = this.mesh.position;
  87896. for (var i = 0; i < len; i++) {
  87897. var bone = bones[i];
  87898. var points = this._debugLines[i];
  87899. if (!points) {
  87900. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87901. this._debugLines[i] = points;
  87902. }
  87903. this._getBonePosition(points[0], bone, meshMat);
  87904. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  87905. points[0].subtractInPlace(meshPos);
  87906. points[1].subtractInPlace(meshPos);
  87907. }
  87908. };
  87909. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  87910. var len = bones.length;
  87911. var boneNum = 0;
  87912. var meshPos = this.mesh.position;
  87913. for (var i = len - 1; i >= 0; i--) {
  87914. var childBone = bones[i];
  87915. var parentBone = childBone.getParent();
  87916. if (!parentBone) {
  87917. continue;
  87918. }
  87919. var points = this._debugLines[boneNum];
  87920. if (!points) {
  87921. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87922. this._debugLines[boneNum] = points;
  87923. }
  87924. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  87925. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  87926. points[0].subtractInPlace(meshPos);
  87927. points[1].subtractInPlace(meshPos);
  87928. boneNum++;
  87929. }
  87930. };
  87931. /** Update the viewer to sync with current skeleton state */
  87932. SkeletonViewer.prototype.update = function () {
  87933. if (this.autoUpdateBonesMatrices) {
  87934. this.skeleton.computeAbsoluteTransforms();
  87935. }
  87936. if (this.skeleton.bones[0].length === undefined) {
  87937. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87938. }
  87939. else {
  87940. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87941. }
  87942. if (!this._debugMesh) {
  87943. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  87944. this._debugMesh.renderingGroupId = this.renderingGroupId;
  87945. }
  87946. else {
  87947. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  87948. }
  87949. this._debugMesh.position.copyFrom(this.mesh.position);
  87950. this._debugMesh.color = this.color;
  87951. };
  87952. /** Release associated resources */
  87953. SkeletonViewer.prototype.dispose = function () {
  87954. if (this._debugMesh) {
  87955. this.isEnabled = false;
  87956. this._debugMesh.dispose();
  87957. this._debugMesh = null;
  87958. }
  87959. };
  87960. return SkeletonViewer;
  87961. }());
  87962. Debug.SkeletonViewer = SkeletonViewer;
  87963. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87964. })(BABYLON || (BABYLON = {}));
  87965. //# sourceMappingURL=babylon.skeletonViewer.js.map
  87966. /**
  87967. * Module Debug contains the (visual) components to debug a scene correctly
  87968. */
  87969. var BABYLON;
  87970. (function (BABYLON) {
  87971. var Debug;
  87972. (function (Debug) {
  87973. /**
  87974. * The Axes viewer will show 3 axes in a specific point in space
  87975. */
  87976. var AxesViewer = /** @class */ (function () {
  87977. /**
  87978. * Creates a new AxesViewer
  87979. * @param scene defines the hosting scene
  87980. * @param scaleLines defines a number used to scale line length (1 by default)
  87981. */
  87982. function AxesViewer(scene, scaleLines) {
  87983. if (scaleLines === void 0) { scaleLines = 1; }
  87984. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87985. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87986. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87987. /**
  87988. * Gets or sets a number used to scale line length
  87989. */
  87990. this.scaleLines = 1;
  87991. this.scaleLines = scaleLines;
  87992. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  87993. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  87994. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  87995. this._xmesh.renderingGroupId = 2;
  87996. this._ymesh.renderingGroupId = 2;
  87997. this._zmesh.renderingGroupId = 2;
  87998. this._xmesh.material.checkReadyOnlyOnce = true;
  87999. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  88000. this._ymesh.material.checkReadyOnlyOnce = true;
  88001. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  88002. this._zmesh.material.checkReadyOnlyOnce = true;
  88003. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  88004. this.scene = scene;
  88005. }
  88006. /**
  88007. * Force the viewer to update
  88008. * @param position defines the position of the viewer
  88009. * @param xaxis defines the x axis of the viewer
  88010. * @param yaxis defines the y axis of the viewer
  88011. * @param zaxis defines the z axis of the viewer
  88012. */
  88013. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  88014. var scaleLines = this.scaleLines;
  88015. if (this._xmesh) {
  88016. this._xmesh.position.copyFrom(position);
  88017. }
  88018. if (this._ymesh) {
  88019. this._ymesh.position.copyFrom(position);
  88020. }
  88021. if (this._zmesh) {
  88022. this._zmesh.position.copyFrom(position);
  88023. }
  88024. var point2 = this._xline[1];
  88025. point2.x = xaxis.x * scaleLines;
  88026. point2.y = xaxis.y * scaleLines;
  88027. point2.z = xaxis.z * scaleLines;
  88028. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  88029. point2 = this._yline[1];
  88030. point2.x = yaxis.x * scaleLines;
  88031. point2.y = yaxis.y * scaleLines;
  88032. point2.z = yaxis.z * scaleLines;
  88033. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  88034. point2 = this._zline[1];
  88035. point2.x = zaxis.x * scaleLines;
  88036. point2.y = zaxis.y * scaleLines;
  88037. point2.z = zaxis.z * scaleLines;
  88038. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  88039. };
  88040. /** Releases resources */
  88041. AxesViewer.prototype.dispose = function () {
  88042. if (this._xmesh) {
  88043. this._xmesh.dispose();
  88044. }
  88045. if (this._ymesh) {
  88046. this._ymesh.dispose();
  88047. }
  88048. if (this._zmesh) {
  88049. this._zmesh.dispose();
  88050. }
  88051. this._xmesh = null;
  88052. this._ymesh = null;
  88053. this._zmesh = null;
  88054. this.scene = null;
  88055. };
  88056. return AxesViewer;
  88057. }());
  88058. Debug.AxesViewer = AxesViewer;
  88059. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88060. })(BABYLON || (BABYLON = {}));
  88061. //# sourceMappingURL=babylon.axesViewer.js.map
  88062. var BABYLON;
  88063. (function (BABYLON) {
  88064. var Debug;
  88065. (function (Debug) {
  88066. /**
  88067. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  88068. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  88069. */
  88070. var BoneAxesViewer = /** @class */ (function (_super) {
  88071. __extends(BoneAxesViewer, _super);
  88072. /**
  88073. * Creates a new BoneAxesViewer
  88074. * @param scene defines the hosting scene
  88075. * @param bone defines the target bone
  88076. * @param mesh defines the target mesh
  88077. * @param scaleLines defines a scaling factor for line length (1 by default)
  88078. */
  88079. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  88080. if (scaleLines === void 0) { scaleLines = 1; }
  88081. var _this = _super.call(this, scene, scaleLines) || this;
  88082. /** Gets current position */
  88083. _this.pos = BABYLON.Vector3.Zero();
  88084. /** Gets direction of X axis */
  88085. _this.xaxis = BABYLON.Vector3.Zero();
  88086. /** Gets direction of Y axis */
  88087. _this.yaxis = BABYLON.Vector3.Zero();
  88088. /** Gets direction of Z axis */
  88089. _this.zaxis = BABYLON.Vector3.Zero();
  88090. _this.mesh = mesh;
  88091. _this.bone = bone;
  88092. return _this;
  88093. }
  88094. /**
  88095. * Force the viewer to update
  88096. */
  88097. BoneAxesViewer.prototype.update = function () {
  88098. if (!this.mesh || !this.bone) {
  88099. return;
  88100. }
  88101. var bone = this.bone;
  88102. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  88103. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  88104. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  88105. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  88106. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  88107. };
  88108. /** Releases resources */
  88109. BoneAxesViewer.prototype.dispose = function () {
  88110. if (this.mesh) {
  88111. this.mesh = null;
  88112. this.bone = null;
  88113. _super.prototype.dispose.call(this);
  88114. }
  88115. };
  88116. return BoneAxesViewer;
  88117. }(Debug.AxesViewer));
  88118. Debug.BoneAxesViewer = BoneAxesViewer;
  88119. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88120. })(BABYLON || (BABYLON = {}));
  88121. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  88122. var BABYLON;
  88123. (function (BABYLON) {
  88124. var RayHelper = /** @class */ (function () {
  88125. function RayHelper(ray) {
  88126. this.ray = ray;
  88127. }
  88128. RayHelper.CreateAndShow = function (ray, scene, color) {
  88129. var helper = new RayHelper(ray);
  88130. helper.show(scene, color);
  88131. return helper;
  88132. };
  88133. RayHelper.prototype.show = function (scene, color) {
  88134. if (!this._renderFunction && this.ray) {
  88135. var ray = this.ray;
  88136. this._renderFunction = this._render.bind(this);
  88137. this._scene = scene;
  88138. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  88139. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  88140. if (this._renderFunction) {
  88141. this._scene.registerBeforeRender(this._renderFunction);
  88142. }
  88143. }
  88144. if (color && this._renderLine) {
  88145. this._renderLine.color.copyFrom(color);
  88146. }
  88147. };
  88148. RayHelper.prototype.hide = function () {
  88149. if (this._renderFunction && this._scene) {
  88150. this._scene.unregisterBeforeRender(this._renderFunction);
  88151. this._scene = null;
  88152. this._renderFunction = null;
  88153. if (this._renderLine) {
  88154. this._renderLine.dispose();
  88155. this._renderLine = null;
  88156. }
  88157. this._renderPoints = [];
  88158. }
  88159. };
  88160. RayHelper.prototype._render = function () {
  88161. var ray = this.ray;
  88162. if (!ray) {
  88163. return;
  88164. }
  88165. var point = this._renderPoints[1];
  88166. var len = Math.min(ray.length, 1000000);
  88167. point.copyFrom(ray.direction);
  88168. point.scaleInPlace(len);
  88169. point.addInPlace(ray.origin);
  88170. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  88171. };
  88172. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  88173. this._attachedToMesh = mesh;
  88174. var ray = this.ray;
  88175. if (!ray) {
  88176. return;
  88177. }
  88178. if (!ray.direction) {
  88179. ray.direction = BABYLON.Vector3.Zero();
  88180. }
  88181. if (!ray.origin) {
  88182. ray.origin = BABYLON.Vector3.Zero();
  88183. }
  88184. if (length) {
  88185. ray.length = length;
  88186. }
  88187. if (!meshSpaceOrigin) {
  88188. meshSpaceOrigin = BABYLON.Vector3.Zero();
  88189. }
  88190. if (!meshSpaceDirection) {
  88191. // -1 so that this will work with Mesh.lookAt
  88192. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  88193. }
  88194. if (!this._meshSpaceDirection) {
  88195. this._meshSpaceDirection = meshSpaceDirection.clone();
  88196. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  88197. }
  88198. else {
  88199. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  88200. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  88201. }
  88202. if (!this._updateToMeshFunction) {
  88203. this._updateToMeshFunction = this._updateToMesh.bind(this);
  88204. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  88205. }
  88206. this._updateToMesh();
  88207. };
  88208. RayHelper.prototype.detachFromMesh = function () {
  88209. if (this._attachedToMesh) {
  88210. if (this._updateToMeshFunction) {
  88211. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  88212. }
  88213. this._attachedToMesh = null;
  88214. this._updateToMeshFunction = null;
  88215. }
  88216. };
  88217. RayHelper.prototype._updateToMesh = function () {
  88218. var ray = this.ray;
  88219. if (!this._attachedToMesh || !ray) {
  88220. return;
  88221. }
  88222. if (this._attachedToMesh._isDisposed) {
  88223. this.detachFromMesh();
  88224. return;
  88225. }
  88226. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  88227. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  88228. };
  88229. RayHelper.prototype.dispose = function () {
  88230. this.hide();
  88231. this.detachFromMesh();
  88232. this.ray = null;
  88233. };
  88234. return RayHelper;
  88235. }());
  88236. BABYLON.RayHelper = RayHelper;
  88237. })(BABYLON || (BABYLON = {}));
  88238. //# sourceMappingURL=babylon.rayHelper.js.map
  88239. var BABYLON;
  88240. (function (BABYLON) {
  88241. // load the inspector using require, if not present in the global namespace.
  88242. var DebugLayer = /** @class */ (function () {
  88243. function DebugLayer(scene) {
  88244. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  88245. this._scene = scene;
  88246. // load inspector using require, if it doesn't exist on the global namespace.
  88247. }
  88248. /** Creates the inspector window. */
  88249. DebugLayer.prototype._createInspector = function (config) {
  88250. if (config === void 0) { config = {}; }
  88251. var popup = config.popup || false;
  88252. var initialTab = config.initialTab || 0;
  88253. var parentElement = config.parentElement || null;
  88254. if (!this._inspector) {
  88255. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  88256. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  88257. } // else nothing to do,; instance is already existing
  88258. };
  88259. DebugLayer.prototype.isVisible = function () {
  88260. if (!this._inspector) {
  88261. return false;
  88262. }
  88263. return true;
  88264. };
  88265. DebugLayer.prototype.hide = function () {
  88266. if (this._inspector) {
  88267. try {
  88268. this._inspector.dispose();
  88269. }
  88270. catch (e) {
  88271. // If the inspector has been removed directly from the inspector tool
  88272. }
  88273. this.onPropertyChangedObservable.clear();
  88274. this._inspector = null;
  88275. }
  88276. };
  88277. /**
  88278. *
  88279. * Launch the debugLayer.
  88280. *
  88281. * initialTab:
  88282. * | Value | Tab Name |
  88283. * | --- | --- |
  88284. * | 0 | Scene |
  88285. * | 1 | Console |
  88286. * | 2 | Stats |
  88287. * | 3 | Textures |
  88288. * | 4 | Mesh |
  88289. * | 5 | Light |
  88290. * | 6 | Material |
  88291. * | 7 | GLTF |
  88292. * | 8 | GUI |
  88293. * | 9 | Physics |
  88294. * | 10 | Camera |
  88295. * | 11 | Audio |
  88296. *
  88297. */
  88298. DebugLayer.prototype.show = function (config) {
  88299. if (config === void 0) { config = {}; }
  88300. if (typeof this.BJSINSPECTOR == 'undefined') {
  88301. // Load inspector and add it to the DOM
  88302. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  88303. }
  88304. else {
  88305. // Otherwise creates the inspector
  88306. this._createInspector(config);
  88307. this.onPropertyChangedObservable = new BABYLON.Observable();
  88308. }
  88309. };
  88310. /**
  88311. * Gets the active tab
  88312. * @return the index of the active tab or -1 if the inspector is hidden
  88313. */
  88314. DebugLayer.prototype.getActiveTab = function () {
  88315. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  88316. };
  88317. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  88318. return DebugLayer;
  88319. }());
  88320. BABYLON.DebugLayer = DebugLayer;
  88321. })(BABYLON || (BABYLON = {}));
  88322. //# sourceMappingURL=babylon.debugLayer.js.map
  88323. var BABYLON;
  88324. (function (BABYLON) {
  88325. var Debug;
  88326. (function (Debug) {
  88327. /**
  88328. * Used to show the physics impostor around the specific mesh
  88329. */
  88330. var PhysicsViewer = /** @class */ (function () {
  88331. /**
  88332. * Creates a new PhysicsViewer
  88333. * @param scene defines the hosting scene
  88334. */
  88335. function PhysicsViewer(scene) {
  88336. /** @hidden */
  88337. this._impostors = [];
  88338. /** @hidden */
  88339. this._meshes = [];
  88340. /** @hidden */
  88341. this._numMeshes = 0;
  88342. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88343. var physicEngine = this._scene.getPhysicsEngine();
  88344. if (physicEngine) {
  88345. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  88346. }
  88347. }
  88348. /** @hidden */
  88349. PhysicsViewer.prototype._updateDebugMeshes = function () {
  88350. var plugin = this._physicsEnginePlugin;
  88351. for (var i = 0; i < this._numMeshes; i++) {
  88352. var impostor = this._impostors[i];
  88353. if (!impostor) {
  88354. continue;
  88355. }
  88356. if (impostor.isDisposed) {
  88357. this.hideImpostor(this._impostors[i--]);
  88358. }
  88359. else {
  88360. var mesh = this._meshes[i];
  88361. if (mesh && plugin) {
  88362. plugin.syncMeshWithImpostor(mesh, impostor);
  88363. }
  88364. }
  88365. }
  88366. };
  88367. /**
  88368. * Renders a specified physic impostor
  88369. * @param impostor defines the impostor to render
  88370. */
  88371. PhysicsViewer.prototype.showImpostor = function (impostor) {
  88372. if (!this._scene) {
  88373. return;
  88374. }
  88375. for (var i = 0; i < this._numMeshes; i++) {
  88376. if (this._impostors[i] == impostor) {
  88377. return;
  88378. }
  88379. }
  88380. var debugMesh = this._getDebugMesh(impostor, this._scene);
  88381. if (debugMesh) {
  88382. this._impostors[this._numMeshes] = impostor;
  88383. this._meshes[this._numMeshes] = debugMesh;
  88384. if (this._numMeshes === 0) {
  88385. this._renderFunction = this._updateDebugMeshes.bind(this);
  88386. this._scene.registerBeforeRender(this._renderFunction);
  88387. }
  88388. this._numMeshes++;
  88389. }
  88390. };
  88391. /**
  88392. * Hides a specified physic impostor
  88393. * @param impostor defines the impostor to hide
  88394. */
  88395. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  88396. if (!impostor || !this._scene) {
  88397. return;
  88398. }
  88399. var removed = false;
  88400. for (var i = 0; i < this._numMeshes; i++) {
  88401. if (this._impostors[i] == impostor) {
  88402. var mesh = this._meshes[i];
  88403. if (!mesh) {
  88404. continue;
  88405. }
  88406. this._scene.removeMesh(mesh);
  88407. mesh.dispose();
  88408. this._numMeshes--;
  88409. if (this._numMeshes > 0) {
  88410. this._meshes[i] = this._meshes[this._numMeshes];
  88411. this._impostors[i] = this._impostors[this._numMeshes];
  88412. this._meshes[this._numMeshes] = null;
  88413. this._impostors[this._numMeshes] = null;
  88414. }
  88415. else {
  88416. this._meshes[0] = null;
  88417. this._impostors[0] = null;
  88418. }
  88419. removed = true;
  88420. break;
  88421. }
  88422. }
  88423. if (removed && this._numMeshes === 0) {
  88424. this._scene.unregisterBeforeRender(this._renderFunction);
  88425. }
  88426. };
  88427. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  88428. if (!this._debugMaterial) {
  88429. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  88430. this._debugMaterial.wireframe = true;
  88431. }
  88432. return this._debugMaterial;
  88433. };
  88434. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  88435. if (!this._debugBoxMesh) {
  88436. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  88437. this._debugBoxMesh.renderingGroupId = 1;
  88438. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88439. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  88440. scene.removeMesh(this._debugBoxMesh);
  88441. }
  88442. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  88443. };
  88444. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  88445. if (!this._debugSphereMesh) {
  88446. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  88447. this._debugSphereMesh.renderingGroupId = 1;
  88448. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88449. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  88450. scene.removeMesh(this._debugSphereMesh);
  88451. }
  88452. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  88453. };
  88454. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  88455. var mesh = null;
  88456. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  88457. mesh = this._getDebugBoxMesh(scene);
  88458. impostor.getBoxSizeToRef(mesh.scaling);
  88459. }
  88460. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  88461. mesh = this._getDebugSphereMesh(scene);
  88462. var radius = impostor.getRadius();
  88463. mesh.scaling.x = radius * 2;
  88464. mesh.scaling.y = radius * 2;
  88465. mesh.scaling.z = radius * 2;
  88466. }
  88467. return mesh;
  88468. };
  88469. /** Releases all resources */
  88470. PhysicsViewer.prototype.dispose = function () {
  88471. for (var i = 0; i < this._numMeshes; i++) {
  88472. this.hideImpostor(this._impostors[i]);
  88473. }
  88474. if (this._debugBoxMesh) {
  88475. this._debugBoxMesh.dispose();
  88476. }
  88477. if (this._debugSphereMesh) {
  88478. this._debugSphereMesh.dispose();
  88479. }
  88480. if (this._debugMaterial) {
  88481. this._debugMaterial.dispose();
  88482. }
  88483. this._impostors.length = 0;
  88484. this._scene = null;
  88485. this._physicsEnginePlugin = null;
  88486. };
  88487. return PhysicsViewer;
  88488. }());
  88489. Debug.PhysicsViewer = PhysicsViewer;
  88490. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88491. })(BABYLON || (BABYLON = {}));
  88492. //# sourceMappingURL=babylon.physicsViewer.js.map
  88493. var BABYLON;
  88494. (function (BABYLON) {
  88495. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  88496. get: function () {
  88497. return this._forceShowBoundingBoxes || false;
  88498. },
  88499. set: function (value) {
  88500. this._forceShowBoundingBoxes = value;
  88501. // Lazyly creates a BB renderer if needed.
  88502. if (value) {
  88503. this.getBoundingBoxRenderer();
  88504. }
  88505. },
  88506. enumerable: true,
  88507. configurable: true
  88508. });
  88509. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  88510. if (!this._boundingBoxRenderer) {
  88511. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  88512. }
  88513. return this._boundingBoxRenderer;
  88514. };
  88515. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  88516. get: function () {
  88517. return this._showBoundingBox || false;
  88518. },
  88519. set: function (value) {
  88520. this._showBoundingBox = value;
  88521. // Lazyly creates a BB renderer if needed.
  88522. if (value) {
  88523. this.getScene().getBoundingBoxRenderer();
  88524. }
  88525. },
  88526. enumerable: true,
  88527. configurable: true
  88528. });
  88529. var BoundingBoxRenderer = /** @class */ (function () {
  88530. function BoundingBoxRenderer(scene) {
  88531. /**
  88532. * The component name helpfull to identify the component in the list of scene components.
  88533. */
  88534. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  88535. this.frontColor = new BABYLON.Color3(1, 1, 1);
  88536. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  88537. this.showBackLines = true;
  88538. this.renderList = new BABYLON.SmartArray(32);
  88539. this._vertexBuffers = {};
  88540. this.scene = scene;
  88541. scene._addComponent(this);
  88542. }
  88543. /**
  88544. * Registers the component in a given scene
  88545. */
  88546. BoundingBoxRenderer.prototype.register = function () {
  88547. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  88548. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  88549. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  88550. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  88551. };
  88552. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  88553. if (mesh.showSubMeshesBoundingBox) {
  88554. var boundingInfo = subMesh.getBoundingInfo();
  88555. if (boundingInfo !== null && boundingInfo !== undefined) {
  88556. this.renderList.push(boundingInfo.boundingBox);
  88557. }
  88558. }
  88559. };
  88560. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  88561. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  88562. var boundingInfo = sourceMesh.getBoundingInfo();
  88563. this.renderList.push(boundingInfo.boundingBox);
  88564. }
  88565. };
  88566. BoundingBoxRenderer.prototype._prepareRessources = function () {
  88567. if (this._colorShader) {
  88568. return;
  88569. }
  88570. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  88571. attributes: [BABYLON.VertexBuffer.PositionKind],
  88572. uniforms: ["world", "viewProjection", "color"]
  88573. });
  88574. var engine = this.scene.getEngine();
  88575. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  88576. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  88577. this._createIndexBuffer();
  88578. };
  88579. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  88580. var engine = this.scene.getEngine();
  88581. 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]);
  88582. };
  88583. /**
  88584. * Rebuilds the elements related to this component in case of
  88585. * context lost for instance.
  88586. */
  88587. BoundingBoxRenderer.prototype.rebuild = function () {
  88588. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88589. if (vb) {
  88590. vb._rebuild();
  88591. }
  88592. this._createIndexBuffer();
  88593. };
  88594. BoundingBoxRenderer.prototype.reset = function () {
  88595. this.renderList.reset();
  88596. };
  88597. BoundingBoxRenderer.prototype.render = function () {
  88598. if (this.renderList.length === 0) {
  88599. return;
  88600. }
  88601. this._prepareRessources();
  88602. if (!this._colorShader.isReady()) {
  88603. return;
  88604. }
  88605. var engine = this.scene.getEngine();
  88606. engine.setDepthWrite(false);
  88607. this._colorShader._preBind();
  88608. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  88609. var boundingBox = this.renderList.data[boundingBoxIndex];
  88610. var min = boundingBox.minimum;
  88611. var max = boundingBox.maximum;
  88612. var diff = max.subtract(min);
  88613. var median = min.add(diff.scale(0.5));
  88614. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88615. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88616. .multiply(boundingBox.getWorldMatrix());
  88617. // VBOs
  88618. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88619. if (this.showBackLines) {
  88620. // Back
  88621. engine.setDepthFunctionToGreaterOrEqual();
  88622. this.scene.resetCachedMaterial();
  88623. this._colorShader.setColor4("color", this.backColor.toColor4());
  88624. this._colorShader.bind(worldMatrix);
  88625. // Draw order
  88626. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88627. }
  88628. // Front
  88629. engine.setDepthFunctionToLess();
  88630. this.scene.resetCachedMaterial();
  88631. this._colorShader.setColor4("color", this.frontColor.toColor4());
  88632. this._colorShader.bind(worldMatrix);
  88633. // Draw order
  88634. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88635. }
  88636. this._colorShader.unbind();
  88637. engine.setDepthFunctionToLessOrEqual();
  88638. engine.setDepthWrite(true);
  88639. };
  88640. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  88641. this._prepareRessources();
  88642. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  88643. return;
  88644. }
  88645. var engine = this.scene.getEngine();
  88646. engine.setDepthWrite(false);
  88647. engine.setColorWrite(false);
  88648. this._colorShader._preBind();
  88649. var boundingBox = mesh._boundingInfo.boundingBox;
  88650. var min = boundingBox.minimum;
  88651. var max = boundingBox.maximum;
  88652. var diff = max.subtract(min);
  88653. var median = min.add(diff.scale(0.5));
  88654. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88655. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88656. .multiply(boundingBox.getWorldMatrix());
  88657. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88658. engine.setDepthFunctionToLess();
  88659. this.scene.resetCachedMaterial();
  88660. this._colorShader.bind(worldMatrix);
  88661. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88662. this._colorShader.unbind();
  88663. engine.setDepthFunctionToLessOrEqual();
  88664. engine.setDepthWrite(true);
  88665. engine.setColorWrite(true);
  88666. };
  88667. BoundingBoxRenderer.prototype.dispose = function () {
  88668. if (!this._colorShader) {
  88669. return;
  88670. }
  88671. this.renderList.dispose();
  88672. this._colorShader.dispose();
  88673. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88674. if (buffer) {
  88675. buffer.dispose();
  88676. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88677. }
  88678. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  88679. };
  88680. return BoundingBoxRenderer;
  88681. }());
  88682. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  88683. })(BABYLON || (BABYLON = {}));
  88684. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  88685. var BABYLON;
  88686. (function (BABYLON) {
  88687. /**
  88688. * Renders a layer on top of an existing scene
  88689. */
  88690. var UtilityLayerRenderer = /** @class */ (function () {
  88691. /**
  88692. * Instantiates a UtilityLayerRenderer
  88693. * @param originalScene the original scene that will be rendered on top of
  88694. */
  88695. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  88696. var _this = this;
  88697. this.originalScene = originalScene;
  88698. this._pointerCaptures = {};
  88699. this._lastPointerEvents = {};
  88700. /**
  88701. * If the utility layer should automatically be rendered on top of existing scene
  88702. */
  88703. this.shouldRender = true;
  88704. /**
  88705. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  88706. */
  88707. this.onlyCheckPointerDownEvents = true;
  88708. /**
  88709. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  88710. */
  88711. this.processAllEvents = false;
  88712. /**
  88713. * Observable raised when the pointer move from the utility layer scene to the main scene
  88714. */
  88715. this.onPointerOutObservable = new BABYLON.Observable();
  88716. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  88717. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  88718. originalScene.getEngine().scenes.pop();
  88719. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  88720. this.utilityLayerScene.detachControl();
  88721. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  88722. if (!_this.processAllEvents) {
  88723. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  88724. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  88725. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  88726. return;
  88727. }
  88728. }
  88729. var pointerEvent = (prePointerInfo.event);
  88730. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  88731. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88732. return;
  88733. }
  88734. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  88735. if (!prePointerInfo.ray && utilityScenePick) {
  88736. prePointerInfo.ray = utilityScenePick.ray;
  88737. }
  88738. // always fire the prepointer oversvable
  88739. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  88740. // allow every non pointer down event to flow to the utility layer
  88741. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  88742. if (!prePointerInfo.skipOnPointerObservable) {
  88743. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88744. }
  88745. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  88746. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88747. }
  88748. return;
  88749. }
  88750. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  88751. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  88752. if (utilityScenePick && utilityScenePick.hit) {
  88753. if (!prePointerInfo.skipOnPointerObservable) {
  88754. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88755. }
  88756. prePointerInfo.skipOnPointerObservable = true;
  88757. }
  88758. }
  88759. else {
  88760. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  88761. var pointerEvent_1 = (prePointerInfo.event);
  88762. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  88763. if (originalScenePick && utilityScenePick) {
  88764. // No pick in utility scene
  88765. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  88766. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88767. // We touched an utility mesh present in the main scene
  88768. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88769. prePointerInfo.skipOnPointerObservable = true;
  88770. }
  88771. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88772. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  88773. }
  88774. }
  88775. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  88776. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  88777. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  88778. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  88779. }
  88780. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  88781. // We have a pick in both scenes but main is closer than utility
  88782. // We touched an utility mesh present in the main scene
  88783. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88784. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88785. prePointerInfo.skipOnPointerObservable = true;
  88786. }
  88787. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  88788. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  88789. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  88790. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  88791. }
  88792. }
  88793. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  88794. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  88795. }
  88796. }
  88797. }
  88798. });
  88799. // Render directly on top of existing scene without clearing
  88800. this.utilityLayerScene.autoClear = false;
  88801. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  88802. if (_this.shouldRender) {
  88803. _this.render();
  88804. }
  88805. });
  88806. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  88807. _this.dispose();
  88808. });
  88809. this._updateCamera();
  88810. }
  88811. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  88812. get: function () {
  88813. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  88814. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  88815. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.add(function () {
  88816. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88817. });
  88818. }
  88819. return UtilityLayerRenderer._DefaultUtilityLayer;
  88820. },
  88821. enumerable: true,
  88822. configurable: true
  88823. });
  88824. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  88825. if (!prePointerInfo.skipOnPointerObservable) {
  88826. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  88827. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  88828. }
  88829. };
  88830. /**
  88831. * Renders the utility layers scene on top of the original scene
  88832. */
  88833. UtilityLayerRenderer.prototype.render = function () {
  88834. this._updateCamera();
  88835. this.utilityLayerScene.render(false);
  88836. };
  88837. /**
  88838. * Disposes of the renderer
  88839. */
  88840. UtilityLayerRenderer.prototype.dispose = function () {
  88841. this.onPointerOutObservable.clear();
  88842. if (this._afterRenderObserver) {
  88843. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  88844. }
  88845. if (this._sceneDisposeObserver) {
  88846. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88847. }
  88848. if (this._originalPointerObserver) {
  88849. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  88850. }
  88851. this.utilityLayerScene.dispose();
  88852. };
  88853. UtilityLayerRenderer.prototype._updateCamera = function () {
  88854. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  88855. };
  88856. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88857. return UtilityLayerRenderer;
  88858. }());
  88859. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  88860. })(BABYLON || (BABYLON = {}));
  88861. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  88862. //# sourceMappingURL=babylon.behavior.js.map
  88863. var BABYLON;
  88864. (function (BABYLON) {
  88865. /**
  88866. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  88867. */
  88868. var PointerDragBehavior = /** @class */ (function () {
  88869. /**
  88870. * Creates a pointer drag behavior that can be attached to a mesh
  88871. * @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)
  88872. */
  88873. function PointerDragBehavior(options) {
  88874. this.options = options;
  88875. /**
  88876. * 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)
  88877. */
  88878. this.maxDragAngle = 0;
  88879. /**
  88880. * @hidden
  88881. */
  88882. this._useAlternatePickedPointAboveMaxDragAngle = false;
  88883. /**
  88884. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88885. */
  88886. this.currentDraggingPointerID = -1;
  88887. /**
  88888. * If the behavior is currently in a dragging state
  88889. */
  88890. this.dragging = false;
  88891. /**
  88892. * 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)
  88893. */
  88894. this.dragDeltaRatio = 0.2;
  88895. /**
  88896. * If the drag plane orientation should be updated during the dragging (Default: true)
  88897. */
  88898. this.updateDragPlane = true;
  88899. // Debug mode will display drag planes to help visualize behavior
  88900. this._debugMode = false;
  88901. this._moving = false;
  88902. /**
  88903. * Fires each time the attached mesh is dragged with the pointer
  88904. * * delta between last drag position and current drag position in world space
  88905. * * dragDistance along the drag axis
  88906. * * dragPlaneNormal normal of the current drag plane used during the drag
  88907. * * dragPlanePoint in world space where the drag intersects the drag plane
  88908. */
  88909. this.onDragObservable = new BABYLON.Observable();
  88910. /**
  88911. * Fires each time a drag begins (eg. mouse down on mesh)
  88912. */
  88913. this.onDragStartObservable = new BABYLON.Observable();
  88914. /**
  88915. * Fires each time a drag ends (eg. mouse release after drag)
  88916. */
  88917. this.onDragEndObservable = new BABYLON.Observable();
  88918. /**
  88919. * If the attached mesh should be moved when dragged
  88920. */
  88921. this.moveAttached = true;
  88922. /**
  88923. * If the drag behavior will react to drag events (Default: true)
  88924. */
  88925. this.enabled = true;
  88926. /**
  88927. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  88928. */
  88929. this.useObjectOrienationForDragging = true;
  88930. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88931. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  88932. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  88933. // Variables to avoid instantiation in the below method
  88934. this._pointA = new BABYLON.Vector3(0, 0, 0);
  88935. this._pointB = new BABYLON.Vector3(0, 0, 0);
  88936. this._pointC = new BABYLON.Vector3(0, 0, 0);
  88937. this._lineA = new BABYLON.Vector3(0, 0, 0);
  88938. this._lineB = new BABYLON.Vector3(0, 0, 0);
  88939. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  88940. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  88941. var optionCount = 0;
  88942. if (options === undefined) {
  88943. options = {};
  88944. }
  88945. if (options.dragAxis) {
  88946. optionCount++;
  88947. }
  88948. if (options.dragPlaneNormal) {
  88949. optionCount++;
  88950. }
  88951. if (optionCount > 1) {
  88952. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  88953. }
  88954. }
  88955. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  88956. /**
  88957. * The name of the behavior
  88958. */
  88959. get: function () {
  88960. return "PointerDrag";
  88961. },
  88962. enumerable: true,
  88963. configurable: true
  88964. });
  88965. /**
  88966. * Initializes the behavior
  88967. */
  88968. PointerDragBehavior.prototype.init = function () { };
  88969. /**
  88970. * Attaches the drag behavior the passed in mesh
  88971. * @param ownerNode The mesh that will be dragged around once attached
  88972. */
  88973. PointerDragBehavior.prototype.attach = function (ownerNode) {
  88974. var _this = this;
  88975. this._scene = ownerNode.getScene();
  88976. this._attachedNode = ownerNode;
  88977. // Initialize drag plane to not interfere with existing scene
  88978. if (!PointerDragBehavior._planeScene) {
  88979. if (this._debugMode) {
  88980. PointerDragBehavior._planeScene = this._scene;
  88981. }
  88982. else {
  88983. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  88984. this._scene.getEngine().scenes.pop();
  88985. }
  88986. }
  88987. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  88988. // State of the drag
  88989. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  88990. var delta = new BABYLON.Vector3(0, 0, 0);
  88991. var dragLength = 0;
  88992. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  88993. var pickPredicate = function (m) {
  88994. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  88995. };
  88996. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88997. if (!_this.enabled) {
  88998. return;
  88999. }
  89000. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89001. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89002. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  89003. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89004. if (pickedPoint) {
  89005. _this.dragging = true;
  89006. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89007. _this.lastDragPosition.copyFrom(pickedPoint);
  89008. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  89009. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  89010. }
  89011. }
  89012. }
  89013. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89014. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89015. _this.releaseDrag();
  89016. }
  89017. }
  89018. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89019. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89020. _this._moving = true;
  89021. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89022. if (pickedPoint) {
  89023. if (_this.updateDragPlane) {
  89024. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  89025. }
  89026. // depending on the drag mode option drag accordingly
  89027. if (_this.options.dragAxis) {
  89028. // Convert local drag axis to world
  89029. BABYLON.Vector3.TransformCoordinatesToRef(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  89030. // Project delta drag from the drag plane onto the drag axis
  89031. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  89032. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  89033. _this._worldDragAxis.scaleToRef(dragLength, delta);
  89034. }
  89035. else {
  89036. dragLength = delta.length();
  89037. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  89038. }
  89039. targetPosition.addInPlace(delta);
  89040. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  89041. _this.lastDragPosition.copyFrom(pickedPoint);
  89042. }
  89043. }
  89044. }
  89045. });
  89046. this._scene.onBeforeRenderObservable.add(function () {
  89047. if (_this._moving && _this.moveAttached) {
  89048. // Slowly move mesh to avoid jitter
  89049. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  89050. _this._tmpVector.scaleInPlace(0.2);
  89051. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  89052. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  89053. }
  89054. });
  89055. };
  89056. PointerDragBehavior.prototype.releaseDrag = function () {
  89057. this.dragging = false;
  89058. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  89059. this.currentDraggingPointerID = -1;
  89060. this._moving = false;
  89061. };
  89062. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  89063. var _this = this;
  89064. if (!ray) {
  89065. return null;
  89066. }
  89067. // Calculate angle between plane normal and ray
  89068. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  89069. // Correct if ray is casted from oposite side
  89070. if (angle > Math.PI / 2) {
  89071. angle = Math.PI - angle;
  89072. }
  89073. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  89074. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  89075. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  89076. // Invert ray direction along the towards object axis
  89077. this._tmpVector.copyFrom(ray.direction);
  89078. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  89079. this._alternatePickedPoint.normalize();
  89080. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  89081. this._tmpVector.addInPlace(this._alternatePickedPoint);
  89082. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  89083. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  89084. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  89085. this._alternatePickedPoint.addInPlace(this._tmpVector);
  89086. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  89087. return this._alternatePickedPoint;
  89088. }
  89089. else {
  89090. return null;
  89091. }
  89092. }
  89093. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  89094. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  89095. return pickResult.pickedPoint;
  89096. }
  89097. else {
  89098. return null;
  89099. }
  89100. };
  89101. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  89102. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  89103. this._pointA.copyFrom(dragPlanePosition);
  89104. if (this.options.dragAxis) {
  89105. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragAxis);
  89106. // Calculate plane normal in direction of camera but perpendicular to drag axis
  89107. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  89108. ray.origin.subtractToRef(this._pointA, this._pointC);
  89109. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  89110. // Get perpendicular line from direction to camera and drag axis
  89111. this._pointB.subtractToRef(this._pointA, this._lineA);
  89112. this._pointC.subtractToRef(this._pointA, this._lineB);
  89113. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  89114. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  89115. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  89116. this._lookAt.normalize();
  89117. this._dragPlane.position.copyFrom(this._pointA);
  89118. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  89119. this._dragPlane.lookAt(this._lookAt);
  89120. }
  89121. else if (this.options.dragPlaneNormal) {
  89122. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragPlaneNormal);
  89123. this._dragPlane.position.copyFrom(this._pointA);
  89124. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  89125. this._dragPlane.lookAt(this._lookAt);
  89126. }
  89127. else {
  89128. this._dragPlane.position.copyFrom(this._pointA);
  89129. this._dragPlane.lookAt(ray.origin);
  89130. }
  89131. this._dragPlane.computeWorldMatrix(true);
  89132. };
  89133. /**
  89134. * Detaches the behavior from the mesh
  89135. */
  89136. PointerDragBehavior.prototype.detach = function () {
  89137. if (this._pointerObserver) {
  89138. this._scene.onPointerObservable.remove(this._pointerObserver);
  89139. }
  89140. };
  89141. return PointerDragBehavior;
  89142. }());
  89143. BABYLON.PointerDragBehavior = PointerDragBehavior;
  89144. })(BABYLON || (BABYLON = {}));
  89145. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  89146. var BABYLON;
  89147. (function (BABYLON) {
  89148. /**
  89149. * A behavior that when attached to a mesh will allow the mesh to be scaled
  89150. */
  89151. var MultiPointerScaleBehavior = /** @class */ (function () {
  89152. function MultiPointerScaleBehavior() {
  89153. this._startDistance = 0;
  89154. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  89155. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  89156. this._sceneRenderObserver = null;
  89157. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  89158. this._dragBehaviorA.moveAttached = false;
  89159. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  89160. this._dragBehaviorB.moveAttached = false;
  89161. }
  89162. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  89163. /**
  89164. * The name of the behavior
  89165. */
  89166. get: function () {
  89167. return "MultiPointerScale";
  89168. },
  89169. enumerable: true,
  89170. configurable: true
  89171. });
  89172. /**
  89173. * Initializes the behavior
  89174. */
  89175. MultiPointerScaleBehavior.prototype.init = function () { };
  89176. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  89177. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  89178. };
  89179. /**
  89180. * Attaches the scale behavior the passed in mesh
  89181. * @param ownerNode The mesh that will be scaled around once attached
  89182. */
  89183. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  89184. var _this = this;
  89185. this._ownerNode = ownerNode;
  89186. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  89187. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  89188. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89189. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89190. _this._dragBehaviorA.releaseDrag();
  89191. }
  89192. else {
  89193. _this._initialScale.copyFrom(ownerNode.scaling);
  89194. _this._startDistance = _this._getCurrentDistance();
  89195. }
  89196. }
  89197. });
  89198. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  89199. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89200. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89201. _this._dragBehaviorB.releaseDrag();
  89202. }
  89203. else {
  89204. _this._initialScale.copyFrom(ownerNode.scaling);
  89205. _this._startDistance = _this._getCurrentDistance();
  89206. }
  89207. }
  89208. });
  89209. // Once both drag behaviors are active scale based on the distance between the two pointers
  89210. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89211. behavior.onDragObservable.add(function () {
  89212. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89213. var ratio = _this._getCurrentDistance() / _this._startDistance;
  89214. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  89215. }
  89216. });
  89217. });
  89218. ownerNode.addBehavior(this._dragBehaviorA);
  89219. ownerNode.addBehavior(this._dragBehaviorB);
  89220. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89221. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89222. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89223. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  89224. if (change.length() > 0.01) {
  89225. ownerNode.scaling.addInPlace(change);
  89226. }
  89227. }
  89228. });
  89229. };
  89230. /**
  89231. * Detaches the behavior from the mesh
  89232. */
  89233. MultiPointerScaleBehavior.prototype.detach = function () {
  89234. var _this = this;
  89235. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89236. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89237. behavior.onDragStartObservable.clear();
  89238. behavior.onDragObservable.clear();
  89239. _this._ownerNode.removeBehavior(behavior);
  89240. });
  89241. };
  89242. return MultiPointerScaleBehavior;
  89243. }());
  89244. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  89245. })(BABYLON || (BABYLON = {}));
  89246. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  89247. var BABYLON;
  89248. (function (BABYLON) {
  89249. /**
  89250. * 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
  89251. */
  89252. var SixDofDragBehavior = /** @class */ (function () {
  89253. function SixDofDragBehavior() {
  89254. this._sceneRenderObserver = null;
  89255. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  89256. this._moving = false;
  89257. this._startingOrientation = new BABYLON.Quaternion();
  89258. /**
  89259. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 5)
  89260. */
  89261. this.zDragFactor = 5;
  89262. /**
  89263. * If the behavior is currently in a dragging state
  89264. */
  89265. this.dragging = false;
  89266. /**
  89267. * 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)
  89268. */
  89269. this.dragDeltaRatio = 0.2;
  89270. /**
  89271. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89272. */
  89273. this.currentDraggingPointerID = -1;
  89274. }
  89275. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  89276. /**
  89277. * The name of the behavior
  89278. */
  89279. get: function () {
  89280. return "SixDofDrag";
  89281. },
  89282. enumerable: true,
  89283. configurable: true
  89284. });
  89285. /**
  89286. * Initializes the behavior
  89287. */
  89288. SixDofDragBehavior.prototype.init = function () { };
  89289. /**
  89290. * Attaches the scale behavior the passed in mesh
  89291. * @param ownerNode The mesh that will be scaled around once attached
  89292. */
  89293. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  89294. var _this = this;
  89295. this._ownerNode = ownerNode;
  89296. this._scene = this._ownerNode.getScene();
  89297. if (!SixDofDragBehavior._virtualScene) {
  89298. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  89299. this._scene.getEngine().scenes.pop();
  89300. }
  89301. var pickedMesh = null;
  89302. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  89303. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  89304. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89305. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  89306. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89307. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  89308. var pickPredicate = function (m) {
  89309. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  89310. };
  89311. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89312. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89313. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89314. pickedMesh = pointerInfo.pickInfo.pickedMesh;
  89315. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89316. // Set position and orientation of the controller
  89317. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89318. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89319. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  89320. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89321. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  89322. if (!pickedMesh.rotationQuaternion) {
  89323. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  89324. }
  89325. var oldParent = pickedMesh.parent;
  89326. pickedMesh.setParent(null);
  89327. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  89328. pickedMesh.setParent(oldParent);
  89329. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89330. // Update state
  89331. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89332. _this.dragging = true;
  89333. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89334. }
  89335. }
  89336. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89337. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89338. _this.dragging = false;
  89339. _this._moving = false;
  89340. _this.currentDraggingPointerID = -1;
  89341. pickedMesh = null;
  89342. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89343. }
  89344. }
  89345. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89346. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  89347. // Calculate controller drag distance in controller space
  89348. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  89349. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89350. var localOriginDragDifference = BABYLON.Vector3.TransformCoordinates(originDragDifference, BABYLON.Matrix.Invert(_this._virtualOriginMesh.getWorldMatrix().getRotationMatrix()));
  89351. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89352. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  89353. var zDragDistance = BABYLON.Vector3.Dot(localOriginDragDifference, _this._virtualOriginMesh.position.normalizeToNew());
  89354. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? zDragDistance * _this.zDragFactor : zDragDistance * _this.zDragFactor * _this._virtualDragMesh.position.z;
  89355. if (_this._virtualDragMesh.position.z < 0) {
  89356. _this._virtualDragMesh.position.z = 0;
  89357. }
  89358. // Update the controller position
  89359. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89360. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89361. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89362. // Move the virtualObjectsPosition into the picked mesh's space if needed
  89363. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89364. if (pickedMesh.parent) {
  89365. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  89366. }
  89367. if (!_this._moving) {
  89368. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  89369. }
  89370. _this._moving = true;
  89371. }
  89372. }
  89373. });
  89374. var tmpQuaternion = new BABYLON.Quaternion();
  89375. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89376. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89377. if (_this.dragging && _this._moving && pickedMesh) {
  89378. // Slowly move mesh to avoid jitter
  89379. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  89380. // Get change in rotation
  89381. tmpQuaternion.copyFrom(_this._startingOrientation);
  89382. tmpQuaternion.x = -tmpQuaternion.x;
  89383. tmpQuaternion.y = -tmpQuaternion.y;
  89384. tmpQuaternion.z = -tmpQuaternion.z;
  89385. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  89386. // Convert change in rotation to only y axis rotation
  89387. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  89388. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  89389. // Slowly move mesh to avoid jitter
  89390. var oldParent = pickedMesh.parent;
  89391. pickedMesh.setParent(null);
  89392. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  89393. pickedMesh.setParent(oldParent);
  89394. }
  89395. });
  89396. };
  89397. /**
  89398. * Detaches the behavior from the mesh
  89399. */
  89400. SixDofDragBehavior.prototype.detach = function () {
  89401. this._scene.onPointerObservable.remove(this._pointerObserver);
  89402. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89403. this._virtualOriginMesh.dispose();
  89404. this._virtualDragMesh.dispose();
  89405. };
  89406. return SixDofDragBehavior;
  89407. }());
  89408. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  89409. })(BABYLON || (BABYLON = {}));
  89410. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  89411. var BABYLON;
  89412. (function (BABYLON) {
  89413. /**
  89414. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  89415. */
  89416. var Gizmo = /** @class */ (function () {
  89417. /**
  89418. * Creates a gizmo
  89419. * @param gizmoLayer The utility layer the gizmo will be added to
  89420. */
  89421. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  89422. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89423. var _this = this;
  89424. this.gizmoLayer = gizmoLayer;
  89425. this._scaleFactor = 3;
  89426. this._tmpMatrix = new BABYLON.Matrix();
  89427. /**
  89428. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  89429. */
  89430. this.updateGizmoRotationToMatchAttachedMesh = true;
  89431. /**
  89432. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  89433. */
  89434. this.updateGizmoPositionToMatchAttachedMesh = true;
  89435. /**
  89436. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  89437. */
  89438. this._updateScale = true;
  89439. this._interactionsEnabled = true;
  89440. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  89441. var tempVector = new BABYLON.Vector3();
  89442. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  89443. if (_this.attachedMesh) {
  89444. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89445. if (!_this._rootMesh.rotationQuaternion) {
  89446. _this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._rootMesh.rotation.y, _this._rootMesh.rotation.x, _this._rootMesh.rotation.z);
  89447. }
  89448. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  89449. tempVector.copyFrom(_this.attachedMesh.scaling);
  89450. if (_this.attachedMesh.scaling.x < 0) {
  89451. _this.attachedMesh.scaling.x *= -1;
  89452. }
  89453. if (_this.attachedMesh.scaling.y < 0) {
  89454. _this.attachedMesh.scaling.y *= -1;
  89455. }
  89456. if (_this.attachedMesh.scaling.z < 0) {
  89457. _this.attachedMesh.scaling.z *= -1;
  89458. }
  89459. _this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89460. _this.attachedMesh.scaling.copyFrom(tempVector);
  89461. _this.attachedMesh.computeWorldMatrix();
  89462. BABYLON.Quaternion.FromRotationMatrixToRef(_this._tmpMatrix, _this._rootMesh.rotationQuaternion);
  89463. }
  89464. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  89465. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  89466. }
  89467. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  89468. _this._rootMesh.position.subtractToRef(_this.gizmoLayer.utilityLayerScene.activeCamera.position, tempVector);
  89469. var dist = tempVector.length() / _this._scaleFactor;
  89470. _this._rootMesh.scaling.set(dist, dist, dist);
  89471. }
  89472. }
  89473. });
  89474. this.attachedMesh = null;
  89475. }
  89476. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  89477. /**
  89478. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  89479. * * When set, interactions will be enabled
  89480. */
  89481. get: function () {
  89482. return this._attachedMesh;
  89483. },
  89484. set: function (value) {
  89485. this._attachedMesh = value;
  89486. this._rootMesh.setEnabled(value ? true : false);
  89487. this._attachedMeshChanged(value);
  89488. },
  89489. enumerable: true,
  89490. configurable: true
  89491. });
  89492. Gizmo.prototype._attachedMeshChanged = function (value) {
  89493. };
  89494. /**
  89495. * Disposes of the gizmo
  89496. */
  89497. Gizmo.prototype.dispose = function () {
  89498. this._rootMesh.dispose();
  89499. if (this._beforeRenderObserver) {
  89500. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89501. }
  89502. };
  89503. return Gizmo;
  89504. }());
  89505. BABYLON.Gizmo = Gizmo;
  89506. })(BABYLON || (BABYLON = {}));
  89507. //# sourceMappingURL=babylon.gizmo.js.map
  89508. var BABYLON;
  89509. (function (BABYLON) {
  89510. /**
  89511. * Single axis drag gizmo
  89512. */
  89513. var AxisDragGizmo = /** @class */ (function (_super) {
  89514. __extends(AxisDragGizmo, _super);
  89515. /**
  89516. * Creates an AxisDragGizmo
  89517. * @param gizmoLayer The utility layer the gizmo will be added to
  89518. * @param dragAxis The axis which the gizmo will be able to drag on
  89519. * @param color The color of the gizmo
  89520. */
  89521. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  89522. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89523. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89524. var _this = _super.call(this, gizmoLayer) || this;
  89525. _this._pointerObserver = null;
  89526. /**
  89527. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89528. */
  89529. _this.snapDistance = 0;
  89530. /**
  89531. * Event that fires each time the gizmo snaps to a new location.
  89532. * * snapDistance is the the change in distance
  89533. */
  89534. _this.onSnapObservable = new BABYLON.Observable();
  89535. // Create Material
  89536. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89537. coloredMaterial.disableLighting = true;
  89538. coloredMaterial.emissiveColor = color;
  89539. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89540. hoverMaterial.disableLighting = true;
  89541. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89542. // Build mesh on root node
  89543. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89544. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89545. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89546. arrow.addChild(arrowMesh);
  89547. arrow.addChild(arrowTail);
  89548. // Position arrow pointing in its drag axis
  89549. arrowMesh.scaling.scaleInPlace(0.05);
  89550. arrowMesh.material = coloredMaterial;
  89551. arrowMesh.rotation.x = Math.PI / 2;
  89552. arrowMesh.position.z += 0.3;
  89553. arrowTail.rotation.x = Math.PI / 2;
  89554. arrowTail.material = coloredMaterial;
  89555. arrowTail.position.z += 0.15;
  89556. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89557. _this._rootMesh.addChild(arrow);
  89558. var currentSnapDragDistance = 0;
  89559. var tmpVector = new BABYLON.Vector3();
  89560. var tmpSnapEvent = { snapDistance: 0 };
  89561. // Add drag behavior to handle events when the gizmo is dragged
  89562. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89563. _this.dragBehavior.moveAttached = false;
  89564. _this._rootMesh.addBehavior(_this.dragBehavior);
  89565. _this.dragBehavior.onDragObservable.add(function (event) {
  89566. if (_this.attachedMesh) {
  89567. // Snapping logic
  89568. if (_this.snapDistance == 0) {
  89569. _this.attachedMesh.position.addInPlace(event.delta);
  89570. }
  89571. else {
  89572. currentSnapDragDistance += event.dragDistance;
  89573. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89574. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  89575. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89576. event.delta.normalizeToRef(tmpVector);
  89577. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  89578. _this.attachedMesh.position.addInPlace(tmpVector);
  89579. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89580. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89581. }
  89582. }
  89583. }
  89584. });
  89585. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89586. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89587. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89588. m.material = hoverMaterial;
  89589. });
  89590. }
  89591. else {
  89592. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89593. m.material = coloredMaterial;
  89594. });
  89595. }
  89596. });
  89597. return _this;
  89598. }
  89599. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  89600. if (this.dragBehavior) {
  89601. this.dragBehavior.enabled = value ? true : false;
  89602. }
  89603. };
  89604. /**
  89605. * Disposes of the gizmo
  89606. */
  89607. AxisDragGizmo.prototype.dispose = function () {
  89608. this.onSnapObservable.clear();
  89609. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89610. this.dragBehavior.detach();
  89611. _super.prototype.dispose.call(this);
  89612. };
  89613. return AxisDragGizmo;
  89614. }(BABYLON.Gizmo));
  89615. BABYLON.AxisDragGizmo = AxisDragGizmo;
  89616. })(BABYLON || (BABYLON = {}));
  89617. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  89618. var BABYLON;
  89619. (function (BABYLON) {
  89620. /**
  89621. * Single axis scale gizmo
  89622. */
  89623. var AxisScaleGizmo = /** @class */ (function (_super) {
  89624. __extends(AxisScaleGizmo, _super);
  89625. /**
  89626. * Creates an AxisScaleGizmo
  89627. * @param gizmoLayer The utility layer the gizmo will be added to
  89628. * @param dragAxis The axis which the gizmo will be able to scale on
  89629. * @param color The color of the gizmo
  89630. */
  89631. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  89632. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89633. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89634. var _this = _super.call(this, gizmoLayer) || this;
  89635. _this._pointerObserver = null;
  89636. /**
  89637. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89638. */
  89639. _this.snapDistance = 0;
  89640. /**
  89641. * Event that fires each time the gizmo snaps to a new location.
  89642. * * snapDistance is the the change in distance
  89643. */
  89644. _this.onSnapObservable = new BABYLON.Observable();
  89645. // Create Material
  89646. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89647. coloredMaterial.disableLighting = true;
  89648. coloredMaterial.emissiveColor = color;
  89649. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89650. hoverMaterial.disableLighting = true;
  89651. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89652. // Build mesh on root node
  89653. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89654. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  89655. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89656. arrow.addChild(arrowMesh);
  89657. arrow.addChild(arrowTail);
  89658. // Position arrow pointing in its drag axis
  89659. arrowMesh.scaling.scaleInPlace(0.1);
  89660. arrowMesh.material = coloredMaterial;
  89661. arrowMesh.rotation.x = Math.PI / 2;
  89662. arrowMesh.position.z += 0.3;
  89663. arrowTail.rotation.x = Math.PI / 2;
  89664. arrowTail.material = coloredMaterial;
  89665. arrowTail.position.z += 0.15;
  89666. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89667. _this._rootMesh.addChild(arrow);
  89668. // Add drag behavior to handle events when the gizmo is dragged
  89669. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89670. _this.dragBehavior.moveAttached = false;
  89671. _this._rootMesh.addBehavior(_this.dragBehavior);
  89672. var currentSnapDragDistance = 0;
  89673. var tmpVector = new BABYLON.Vector3();
  89674. var tmpSnapEvent = { snapDistance: 0 };
  89675. _this.dragBehavior.onDragObservable.add(function (event) {
  89676. if (_this.attachedMesh) {
  89677. // Snapping logic
  89678. var snapped = false;
  89679. var dragSteps = 0;
  89680. if (_this.snapDistance == 0) {
  89681. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  89682. }
  89683. else {
  89684. currentSnapDragDistance += event.dragDistance;
  89685. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89686. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89687. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89688. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  89689. snapped = true;
  89690. }
  89691. else {
  89692. tmpVector.scaleInPlace(0);
  89693. }
  89694. }
  89695. _this.attachedMesh.scaling.addInPlace(tmpVector);
  89696. if (snapped) {
  89697. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89698. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89699. }
  89700. }
  89701. });
  89702. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89703. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89704. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89705. m.material = hoverMaterial;
  89706. });
  89707. }
  89708. else {
  89709. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89710. m.material = coloredMaterial;
  89711. });
  89712. }
  89713. });
  89714. return _this;
  89715. }
  89716. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  89717. if (this.dragBehavior) {
  89718. this.dragBehavior.enabled = value ? true : false;
  89719. }
  89720. };
  89721. /**
  89722. * Disposes of the gizmo
  89723. */
  89724. AxisScaleGizmo.prototype.dispose = function () {
  89725. this.onSnapObservable.clear();
  89726. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89727. this.dragBehavior.detach();
  89728. _super.prototype.dispose.call(this);
  89729. };
  89730. return AxisScaleGizmo;
  89731. }(BABYLON.Gizmo));
  89732. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  89733. })(BABYLON || (BABYLON = {}));
  89734. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  89735. var BABYLON;
  89736. (function (BABYLON) {
  89737. /**
  89738. * Single plane rotation gizmo
  89739. */
  89740. var PlaneRotationGizmo = /** @class */ (function (_super) {
  89741. __extends(PlaneRotationGizmo, _super);
  89742. /**
  89743. * Creates a PlaneRotationGizmo
  89744. * @param gizmoLayer The utility layer the gizmo will be added to
  89745. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  89746. * @param color The color of the gizmo
  89747. */
  89748. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  89749. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89750. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89751. var _this = _super.call(this, gizmoLayer) || this;
  89752. _this._pointerObserver = null;
  89753. /**
  89754. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  89755. */
  89756. _this.snapDistance = 0;
  89757. /**
  89758. * Event that fires each time the gizmo snaps to a new location.
  89759. * * snapDistance is the the change in distance
  89760. */
  89761. _this.onSnapObservable = new BABYLON.Observable();
  89762. // Create Material
  89763. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89764. coloredMaterial.disableLighting = true;
  89765. coloredMaterial.emissiveColor = color;
  89766. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89767. hoverMaterial.disableLighting = true;
  89768. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89769. // Build mesh on root node
  89770. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89771. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  89772. // Position arrow pointing in its drag axis
  89773. rotationMesh.scaling.scaleInPlace(0.1);
  89774. rotationMesh.material = coloredMaterial;
  89775. rotationMesh.rotation.x = Math.PI / 2;
  89776. parentMesh.addChild(rotationMesh);
  89777. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  89778. _this._rootMesh.addChild(parentMesh);
  89779. // Add drag behavior to handle events when the gizmo is dragged
  89780. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  89781. _this.dragBehavior.moveAttached = false;
  89782. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  89783. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  89784. _this._rootMesh.addBehavior(_this.dragBehavior);
  89785. var lastDragPosition = new BABYLON.Vector3();
  89786. _this.dragBehavior.onDragStartObservable.add(function (e) {
  89787. if (_this.attachedMesh) {
  89788. lastDragPosition.copyFrom(e.dragPlanePoint);
  89789. }
  89790. });
  89791. var rotationMatrix = new BABYLON.Matrix();
  89792. var planeNormalTowardsCamera = new BABYLON.Vector3();
  89793. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  89794. var tmpSnapEvent = { snapDistance: 0 };
  89795. var currentSnapDragDistance = 0;
  89796. _this.dragBehavior.onDragObservable.add(function (event) {
  89797. if (_this.attachedMesh) {
  89798. if (!_this.attachedMesh.rotationQuaternion) {
  89799. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  89800. }
  89801. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  89802. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  89803. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  89804. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  89805. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  89806. var angle = Math.atan2(cross.length(), dot);
  89807. planeNormalTowardsCamera.copyFrom(planeNormal);
  89808. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  89809. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89810. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  89811. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  89812. }
  89813. // Flip up vector depending on which side the camera is on
  89814. if (gizmoLayer.utilityLayerScene.activeCamera) {
  89815. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  89816. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  89817. planeNormalTowardsCamera.scaleInPlace(-1);
  89818. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  89819. }
  89820. }
  89821. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  89822. if (halfCircleSide)
  89823. angle = -angle;
  89824. // Snapping logic
  89825. var snapped = false;
  89826. if (_this.snapDistance != 0) {
  89827. currentSnapDragDistance += angle;
  89828. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89829. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89830. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89831. angle = _this.snapDistance * dragSteps;
  89832. snapped = true;
  89833. }
  89834. else {
  89835. angle = 0;
  89836. }
  89837. }
  89838. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  89839. var quaternionCoefficient = Math.sin(angle / 2);
  89840. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  89841. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89842. // Rotate selected mesh quaternion over fixed axis
  89843. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  89844. }
  89845. else {
  89846. // Rotate selected mesh quaternion over rotated axis
  89847. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  89848. }
  89849. lastDragPosition.copyFrom(event.dragPlanePoint);
  89850. if (snapped) {
  89851. tmpSnapEvent.snapDistance = angle;
  89852. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89853. }
  89854. }
  89855. });
  89856. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89857. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89858. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89859. m.material = hoverMaterial;
  89860. });
  89861. }
  89862. else {
  89863. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89864. m.material = coloredMaterial;
  89865. });
  89866. }
  89867. });
  89868. return _this;
  89869. }
  89870. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  89871. if (this.dragBehavior) {
  89872. this.dragBehavior.enabled = value ? true : false;
  89873. }
  89874. };
  89875. /**
  89876. * Disposes of the gizmo
  89877. */
  89878. PlaneRotationGizmo.prototype.dispose = function () {
  89879. this.onSnapObservable.clear();
  89880. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89881. this.dragBehavior.detach();
  89882. _super.prototype.dispose.call(this);
  89883. };
  89884. return PlaneRotationGizmo;
  89885. }(BABYLON.Gizmo));
  89886. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  89887. })(BABYLON || (BABYLON = {}));
  89888. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  89889. var BABYLON;
  89890. (function (BABYLON) {
  89891. /**
  89892. * Gizmo that enables dragging a mesh along 3 axis
  89893. */
  89894. var PositionGizmo = /** @class */ (function (_super) {
  89895. __extends(PositionGizmo, _super);
  89896. /**
  89897. * Creates a PositionGizmo
  89898. * @param gizmoLayer The utility layer the gizmo will be added to
  89899. */
  89900. function PositionGizmo(gizmoLayer) {
  89901. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89902. var _this = _super.call(this, gizmoLayer) || this;
  89903. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89904. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89905. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89906. _this.attachedMesh = null;
  89907. return _this;
  89908. }
  89909. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  89910. set: function (mesh) {
  89911. if (this.xGizmo) {
  89912. this.xGizmo.attachedMesh = mesh;
  89913. this.yGizmo.attachedMesh = mesh;
  89914. this.zGizmo.attachedMesh = mesh;
  89915. }
  89916. },
  89917. enumerable: true,
  89918. configurable: true
  89919. });
  89920. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89921. get: function () {
  89922. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  89923. },
  89924. set: function (value) {
  89925. if (this.xGizmo) {
  89926. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89927. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89928. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89929. }
  89930. },
  89931. enumerable: true,
  89932. configurable: true
  89933. });
  89934. /**
  89935. * Disposes of the gizmo
  89936. */
  89937. PositionGizmo.prototype.dispose = function () {
  89938. this.xGizmo.dispose();
  89939. this.yGizmo.dispose();
  89940. this.zGizmo.dispose();
  89941. };
  89942. return PositionGizmo;
  89943. }(BABYLON.Gizmo));
  89944. BABYLON.PositionGizmo = PositionGizmo;
  89945. })(BABYLON || (BABYLON = {}));
  89946. //# sourceMappingURL=babylon.positionGizmo.js.map
  89947. var BABYLON;
  89948. (function (BABYLON) {
  89949. /**
  89950. * Gizmo that enables rotating a mesh along 3 axis
  89951. */
  89952. var RotationGizmo = /** @class */ (function (_super) {
  89953. __extends(RotationGizmo, _super);
  89954. /**
  89955. * Creates a RotationGizmo
  89956. * @param gizmoLayer The utility layer the gizmo will be added to
  89957. */
  89958. function RotationGizmo(gizmoLayer) {
  89959. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89960. var _this = _super.call(this, gizmoLayer) || this;
  89961. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89962. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89963. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89964. _this.attachedMesh = null;
  89965. return _this;
  89966. }
  89967. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  89968. set: function (mesh) {
  89969. if (this.xGizmo) {
  89970. this.xGizmo.attachedMesh = mesh;
  89971. this.yGizmo.attachedMesh = mesh;
  89972. this.zGizmo.attachedMesh = mesh;
  89973. }
  89974. },
  89975. enumerable: true,
  89976. configurable: true
  89977. });
  89978. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89979. get: function () {
  89980. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  89981. },
  89982. set: function (value) {
  89983. if (this.xGizmo) {
  89984. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89985. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89986. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89987. }
  89988. },
  89989. enumerable: true,
  89990. configurable: true
  89991. });
  89992. /**
  89993. * Disposes of the gizmo
  89994. */
  89995. RotationGizmo.prototype.dispose = function () {
  89996. this.xGizmo.dispose();
  89997. this.yGizmo.dispose();
  89998. this.zGizmo.dispose();
  89999. };
  90000. return RotationGizmo;
  90001. }(BABYLON.Gizmo));
  90002. BABYLON.RotationGizmo = RotationGizmo;
  90003. })(BABYLON || (BABYLON = {}));
  90004. //# sourceMappingURL=babylon.rotationGizmo.js.map
  90005. var BABYLON;
  90006. (function (BABYLON) {
  90007. /**
  90008. * Gizmo that enables scaling a mesh along 3 axis
  90009. */
  90010. var ScaleGizmo = /** @class */ (function (_super) {
  90011. __extends(ScaleGizmo, _super);
  90012. /**
  90013. * Creates a ScaleGizmo
  90014. * @param gizmoLayer The utility layer the gizmo will be added to
  90015. */
  90016. function ScaleGizmo(gizmoLayer) {
  90017. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90018. var _this = _super.call(this, gizmoLayer) || this;
  90019. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90020. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90021. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90022. _this.attachedMesh = null;
  90023. return _this;
  90024. }
  90025. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  90026. set: function (mesh) {
  90027. if (this.xGizmo) {
  90028. this.xGizmo.attachedMesh = mesh;
  90029. this.yGizmo.attachedMesh = mesh;
  90030. this.zGizmo.attachedMesh = mesh;
  90031. }
  90032. },
  90033. enumerable: true,
  90034. configurable: true
  90035. });
  90036. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90037. get: function () {
  90038. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90039. },
  90040. set: function (value) {
  90041. if (this.xGizmo) {
  90042. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90043. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90044. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90045. }
  90046. },
  90047. enumerable: true,
  90048. configurable: true
  90049. });
  90050. /**
  90051. * Disposes of the gizmo
  90052. */
  90053. ScaleGizmo.prototype.dispose = function () {
  90054. this.xGizmo.dispose();
  90055. this.yGizmo.dispose();
  90056. this.zGizmo.dispose();
  90057. };
  90058. return ScaleGizmo;
  90059. }(BABYLON.Gizmo));
  90060. BABYLON.ScaleGizmo = ScaleGizmo;
  90061. })(BABYLON || (BABYLON = {}));
  90062. //# sourceMappingURL=babylon.scaleGizmo.js.map
  90063. var BABYLON;
  90064. (function (BABYLON) {
  90065. /**
  90066. * Bounding box gizmo
  90067. */
  90068. var BoundingBoxGizmo = /** @class */ (function (_super) {
  90069. __extends(BoundingBoxGizmo, _super);
  90070. /**
  90071. * Creates an BoundingBoxGizmo
  90072. * @param gizmoLayer The utility layer the gizmo will be added to
  90073. * @param color The color of the gizmo
  90074. */
  90075. function BoundingBoxGizmo(color, gizmoLayer) {
  90076. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90077. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90078. var _this = _super.call(this, gizmoLayer) || this;
  90079. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  90080. _this._renderObserver = null;
  90081. _this._pointerObserver = null;
  90082. _this._scaleDragSpeed = 0.2;
  90083. _this._tmpQuaternion = new BABYLON.Quaternion();
  90084. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  90085. /**
  90086. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  90087. */
  90088. _this.rotationSphereSize = 0.1;
  90089. /**
  90090. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  90091. */
  90092. _this.scaleBoxSize = 0.1;
  90093. /**
  90094. * 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)
  90095. */
  90096. _this.fixedDragMeshScreenSize = false;
  90097. /**
  90098. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  90099. */
  90100. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  90101. /**
  90102. * Fired when a rotation sphere or scale box is dragged
  90103. */
  90104. _this.onDragStartObservable = new BABYLON.Observable();
  90105. /**
  90106. * Fired when a rotation sphere or scale box drag is started
  90107. */
  90108. _this.onDragObservable = new BABYLON.Observable();
  90109. /**
  90110. * Fired when a rotation sphere or scale box drag is needed
  90111. */
  90112. _this.onDragEndObservable = new BABYLON.Observable();
  90113. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  90114. _this._updateScale = false;
  90115. // Create Materials
  90116. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90117. coloredMaterial.disableLighting = true;
  90118. coloredMaterial.emissiveColor = color;
  90119. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90120. hoverColoredMaterial.disableLighting = true;
  90121. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90122. // Build bounding box out of lines
  90123. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90124. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  90125. var lines = [];
  90126. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  90127. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90128. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90129. 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));
  90130. 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));
  90131. 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));
  90132. 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));
  90133. 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));
  90134. 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));
  90135. 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));
  90136. 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));
  90137. 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));
  90138. lines.forEach(function (l) {
  90139. l.color = color;
  90140. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  90141. l.isPickable = false;
  90142. _this._lineBoundingBox.addChild(l);
  90143. });
  90144. _this._rootMesh.addChild(_this._lineBoundingBox);
  90145. // Create rotation spheres
  90146. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90147. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  90148. var _loop_1 = function (i_1) {
  90149. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  90150. sphere.rotationQuaternion = new BABYLON.Quaternion();
  90151. sphere.material = coloredMaterial;
  90152. // Drag behavior
  90153. _dragBehavior = new BABYLON.PointerDragBehavior({});
  90154. _dragBehavior.moveAttached = false;
  90155. _dragBehavior.updateDragPlane = false;
  90156. sphere.addBehavior(_dragBehavior);
  90157. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  90158. var totalTurnAmountOfDrag = 0;
  90159. _dragBehavior.onDragStartObservable.add(function (event) {
  90160. startingTurnDirection.copyFrom(sphere.forward);
  90161. totalTurnAmountOfDrag = 0;
  90162. });
  90163. _dragBehavior.onDragObservable.add(function (event) {
  90164. _this.onDragObservable.notifyObservers({});
  90165. if (_this.attachedMesh) {
  90166. var worldDragDirection = startingTurnDirection;
  90167. // Project the world right on to the drag plane
  90168. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  90169. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  90170. // project drag delta on to the resulting drag axis and rotate based on that
  90171. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  90172. // Rotate based on axis
  90173. if (!_this.attachedMesh.rotationQuaternion) {
  90174. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90175. }
  90176. // Do not allow the object to turn more than a full circle
  90177. totalTurnAmountOfDrag += projectDist;
  90178. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  90179. if (i_1 >= 8) {
  90180. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  90181. }
  90182. else if (i_1 >= 4) {
  90183. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  90184. }
  90185. else {
  90186. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  90187. }
  90188. _this.attachedMesh.rotationQuaternion.multiplyInPlace(_this._tmpQuaternion);
  90189. }
  90190. }
  90191. });
  90192. // Selection/deselection
  90193. _dragBehavior.onDragStartObservable.add(function () {
  90194. _this.onDragStartObservable.notifyObservers({});
  90195. _this._selectNode(sphere);
  90196. });
  90197. _dragBehavior.onDragEndObservable.add(function () {
  90198. _this.onDragEndObservable.notifyObservers({});
  90199. _this._selectNode(null);
  90200. });
  90201. this_1._rotateSpheresParent.addChild(sphere);
  90202. };
  90203. var this_1 = this, _dragBehavior;
  90204. for (var i_1 = 0; i_1 < 12; i_1++) {
  90205. _loop_1(i_1);
  90206. }
  90207. _this._rootMesh.addChild(_this._rotateSpheresParent);
  90208. // Create scale cubes
  90209. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90210. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  90211. for (var i = 0; i < 2; i++) {
  90212. for (var j = 0; j < 2; j++) {
  90213. var _loop_2 = function () {
  90214. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  90215. box.material = coloredMaterial;
  90216. // Dragging logic
  90217. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  90218. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90219. _dragBehavior.moveAttached = false;
  90220. box.addBehavior(_dragBehavior);
  90221. _dragBehavior.onDragObservable.add(function (event) {
  90222. _this.onDragObservable.notifyObservers({});
  90223. if (_this.attachedMesh) {
  90224. // Current boudning box dimensions
  90225. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  90226. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  90227. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  90228. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  90229. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  90230. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  90231. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  90232. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  90233. // Update scale and position
  90234. _this.attachedMesh.scaling.addInPlace(deltaScale);
  90235. if (_this.attachedMesh.scaling.x < 0 || _this.attachedMesh.scaling.y < 0 || _this.attachedMesh.scaling.z < 0) {
  90236. _this.attachedMesh.scaling.subtractInPlace(deltaScale);
  90237. }
  90238. else {
  90239. _this.attachedMesh.getAbsolutePosition().addToRef(worldMoveDirection, _this._tmpVector);
  90240. _this.attachedMesh.setAbsolutePosition(_this._tmpVector);
  90241. }
  90242. }
  90243. });
  90244. // Selection/deselection
  90245. _dragBehavior.onDragStartObservable.add(function () {
  90246. _this.onDragStartObservable.notifyObservers({});
  90247. _this._selectNode(box);
  90248. });
  90249. _dragBehavior.onDragEndObservable.add(function () {
  90250. _this.onDragEndObservable.notifyObservers({});
  90251. _this._selectNode(null);
  90252. });
  90253. this_2._scaleBoxesParent.addChild(box);
  90254. };
  90255. var this_2 = this, _dragBehavior;
  90256. for (var k = 0; k < 2; k++) {
  90257. _loop_2();
  90258. }
  90259. }
  90260. }
  90261. _this._rootMesh.addChild(_this._scaleBoxesParent);
  90262. // Hover color change
  90263. var pointerIds = new Array();
  90264. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90265. if (!pointerIds[pointerInfo.event.pointerId]) {
  90266. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  90267. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  90268. pointerIds[pointerInfo.event.pointerId] = mesh;
  90269. mesh.material = hoverColoredMaterial;
  90270. }
  90271. });
  90272. }
  90273. else {
  90274. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  90275. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  90276. delete pointerIds[pointerInfo.event.pointerId];
  90277. }
  90278. }
  90279. });
  90280. // Update bounding box positions
  90281. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  90282. _this._updateBoundingBox();
  90283. });
  90284. _this._updateBoundingBox();
  90285. return _this;
  90286. }
  90287. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  90288. this._rotateSpheresParent.getChildMeshes()
  90289. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  90290. m.isVisible = (!selectedMesh || m == selectedMesh);
  90291. });
  90292. };
  90293. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  90294. if (this.attachedMesh) {
  90295. // Update bounding dimensions/positions
  90296. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  90297. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  90298. this._boundingDimensions.copyFrom(boundBoxDimensions);
  90299. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  90300. }
  90301. // Update rotation sphere locations
  90302. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  90303. for (var i = 0; i < 3; i++) {
  90304. for (var j = 0; j < 2; j++) {
  90305. for (var k = 0; k < 2; k++) {
  90306. var index = ((i * 4) + (j * 2)) + k;
  90307. if (i == 0) {
  90308. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90309. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90310. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90311. }
  90312. if (i == 1) {
  90313. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  90314. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90315. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90316. }
  90317. if (i == 2) {
  90318. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  90319. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90320. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90321. }
  90322. if (this.fixedDragMeshScreenSize) {
  90323. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90324. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90325. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90326. }
  90327. else {
  90328. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  90329. }
  90330. }
  90331. }
  90332. }
  90333. // Update scale box locations
  90334. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  90335. for (var i = 0; i < 2; i++) {
  90336. for (var j = 0; j < 2; j++) {
  90337. for (var k = 0; k < 2; k++) {
  90338. var index = ((i * 4) + (j * 2)) + k;
  90339. if (scaleBoxes[index]) {
  90340. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90341. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90342. if (this.fixedDragMeshScreenSize) {
  90343. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90344. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90345. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90346. }
  90347. else {
  90348. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  90349. }
  90350. }
  90351. }
  90352. }
  90353. }
  90354. };
  90355. /**
  90356. * Enables rotation on the specified axis and disables rotation on the others
  90357. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  90358. */
  90359. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  90360. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  90361. if (i < 4) {
  90362. m.setEnabled(axis.indexOf("x") != -1);
  90363. }
  90364. else if (i < 8) {
  90365. m.setEnabled(axis.indexOf("y") != -1);
  90366. }
  90367. else {
  90368. m.setEnabled(axis.indexOf("z") != -1);
  90369. }
  90370. });
  90371. };
  90372. /**
  90373. * Disposes of the gizmo
  90374. */
  90375. BoundingBoxGizmo.prototype.dispose = function () {
  90376. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90377. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  90378. this._lineBoundingBox.dispose();
  90379. this._rotateSpheresParent.dispose();
  90380. this._scaleBoxesParent.dispose();
  90381. _super.prototype.dispose.call(this);
  90382. };
  90383. return BoundingBoxGizmo;
  90384. }(BABYLON.Gizmo));
  90385. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  90386. })(BABYLON || (BABYLON = {}));
  90387. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  90388. var BABYLON;
  90389. (function (BABYLON) {
  90390. /**
  90391. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  90392. */
  90393. var GizmoManager = /** @class */ (function () {
  90394. /**
  90395. * Instatiates a gizmo manager
  90396. * @param scene the scene to overlay the gizmos on top of
  90397. * @param options If only a single gizmo should exist at one time
  90398. */
  90399. function GizmoManager(scene, options) {
  90400. var _this = this;
  90401. this.scene = scene;
  90402. // Set of gizmos that are currently in the scene for each mesh
  90403. this._gizmoSet = {};
  90404. this._pointerObserver = null;
  90405. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  90406. // Options parsing
  90407. if (!options) {
  90408. options = {};
  90409. }
  90410. if (options.singleGizmo === undefined) {
  90411. options.singleGizmo = true;
  90412. }
  90413. // Instatiate/dispose gizmos based on pointer actions
  90414. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  90415. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  90416. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  90417. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  90418. if (options.singleGizmo) {
  90419. _this._clearGizmos();
  90420. }
  90421. // Enable gizmo when mesh is selected
  90422. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  90423. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  90424. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  90425. }
  90426. else {
  90427. if (!options.singleGizmo) {
  90428. // Disable gizmo when clicked again
  90429. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  90430. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  90431. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  90432. }
  90433. }
  90434. }
  90435. else {
  90436. if (options.singleGizmo) {
  90437. // Disable gizmo when clicked away
  90438. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  90439. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  90440. if (gizmoPick && !gizmoPick.hit) {
  90441. _this._clearGizmos();
  90442. }
  90443. }
  90444. }
  90445. }
  90446. }
  90447. });
  90448. }
  90449. /**
  90450. * Disposes of the gizmo manager
  90451. */
  90452. GizmoManager.prototype.dispose = function () {
  90453. this.scene.onPointerObservable.remove(this._pointerObserver);
  90454. this._clearGizmos();
  90455. this._gizmoLayer.dispose();
  90456. };
  90457. GizmoManager.prototype._clearGizmos = function () {
  90458. for (var key in this._gizmoSet) {
  90459. if (this._gizmoSet.hasOwnProperty(key)) {
  90460. this._gizmoSet[key].positionGizmo.dispose();
  90461. this._gizmoSet[key].rotationGizmo.dispose();
  90462. delete this._gizmoSet[key];
  90463. }
  90464. }
  90465. };
  90466. return GizmoManager;
  90467. }());
  90468. BABYLON.GizmoManager = GizmoManager;
  90469. })(BABYLON || (BABYLON = {}));
  90470. //# sourceMappingURL=babylon.gizmoManager.js.map
  90471. var BABYLON;
  90472. (function (BABYLON) {
  90473. /**
  90474. * Defines a target to use with MorphTargetManager
  90475. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90476. */
  90477. var MorphTarget = /** @class */ (function () {
  90478. /**
  90479. * Creates a new MorphTarget
  90480. * @param name defines the name of the target
  90481. * @param influence defines the influence to use
  90482. */
  90483. function MorphTarget(
  90484. /** defines the name of the target */
  90485. name, influence, scene) {
  90486. if (influence === void 0) { influence = 0; }
  90487. if (scene === void 0) { scene = null; }
  90488. this.name = name;
  90489. /**
  90490. * Gets or sets the list of animations
  90491. */
  90492. this.animations = new Array();
  90493. this._positions = null;
  90494. this._normals = null;
  90495. this._tangents = null;
  90496. /**
  90497. * Observable raised when the influence changes
  90498. */
  90499. this.onInfluenceChanged = new BABYLON.Observable();
  90500. this._animationPropertiesOverride = null;
  90501. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90502. this.influence = influence;
  90503. }
  90504. Object.defineProperty(MorphTarget.prototype, "influence", {
  90505. /**
  90506. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  90507. */
  90508. get: function () {
  90509. return this._influence;
  90510. },
  90511. set: function (influence) {
  90512. if (this._influence === influence) {
  90513. return;
  90514. }
  90515. var previous = this._influence;
  90516. this._influence = influence;
  90517. if (this.onInfluenceChanged.hasObservers) {
  90518. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  90519. }
  90520. },
  90521. enumerable: true,
  90522. configurable: true
  90523. });
  90524. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  90525. /**
  90526. * Gets or sets the animation properties override
  90527. */
  90528. get: function () {
  90529. if (!this._animationPropertiesOverride && this._scene) {
  90530. return this._scene.animationPropertiesOverride;
  90531. }
  90532. return this._animationPropertiesOverride;
  90533. },
  90534. set: function (value) {
  90535. this._animationPropertiesOverride = value;
  90536. },
  90537. enumerable: true,
  90538. configurable: true
  90539. });
  90540. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  90541. /**
  90542. * Gets a boolean defining if the target contains position data
  90543. */
  90544. get: function () {
  90545. return !!this._positions;
  90546. },
  90547. enumerable: true,
  90548. configurable: true
  90549. });
  90550. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  90551. /**
  90552. * Gets a boolean defining if the target contains normal data
  90553. */
  90554. get: function () {
  90555. return !!this._normals;
  90556. },
  90557. enumerable: true,
  90558. configurable: true
  90559. });
  90560. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  90561. /**
  90562. * Gets a boolean defining if the target contains tangent data
  90563. */
  90564. get: function () {
  90565. return !!this._tangents;
  90566. },
  90567. enumerable: true,
  90568. configurable: true
  90569. });
  90570. /**
  90571. * Affects position data to this target
  90572. * @param data defines the position data to use
  90573. */
  90574. MorphTarget.prototype.setPositions = function (data) {
  90575. this._positions = data;
  90576. };
  90577. /**
  90578. * Gets the position data stored in this target
  90579. * @returns a FloatArray containing the position data (or null if not present)
  90580. */
  90581. MorphTarget.prototype.getPositions = function () {
  90582. return this._positions;
  90583. };
  90584. /**
  90585. * Affects normal data to this target
  90586. * @param data defines the normal data to use
  90587. */
  90588. MorphTarget.prototype.setNormals = function (data) {
  90589. this._normals = data;
  90590. };
  90591. /**
  90592. * Gets the normal data stored in this target
  90593. * @returns a FloatArray containing the normal data (or null if not present)
  90594. */
  90595. MorphTarget.prototype.getNormals = function () {
  90596. return this._normals;
  90597. };
  90598. /**
  90599. * Affects tangent data to this target
  90600. * @param data defines the tangent data to use
  90601. */
  90602. MorphTarget.prototype.setTangents = function (data) {
  90603. this._tangents = data;
  90604. };
  90605. /**
  90606. * Gets the tangent data stored in this target
  90607. * @returns a FloatArray containing the tangent data (or null if not present)
  90608. */
  90609. MorphTarget.prototype.getTangents = function () {
  90610. return this._tangents;
  90611. };
  90612. /**
  90613. * Serializes the current target into a Serialization object
  90614. * @returns the serialized object
  90615. */
  90616. MorphTarget.prototype.serialize = function () {
  90617. var serializationObject = {};
  90618. serializationObject.name = this.name;
  90619. serializationObject.influence = this.influence;
  90620. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  90621. if (this.hasNormals) {
  90622. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  90623. }
  90624. if (this.hasTangents) {
  90625. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  90626. }
  90627. // Animations
  90628. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  90629. return serializationObject;
  90630. };
  90631. // Statics
  90632. /**
  90633. * Creates a new target from serialized data
  90634. * @param serializationObject defines the serialized data to use
  90635. * @returns a new MorphTarget
  90636. */
  90637. MorphTarget.Parse = function (serializationObject) {
  90638. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  90639. result.setPositions(serializationObject.positions);
  90640. if (serializationObject.normals) {
  90641. result.setNormals(serializationObject.normals);
  90642. }
  90643. if (serializationObject.tangents) {
  90644. result.setTangents(serializationObject.tangents);
  90645. }
  90646. // Animations
  90647. if (serializationObject.animations) {
  90648. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  90649. var parsedAnimation = serializationObject.animations[animationIndex];
  90650. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  90651. }
  90652. }
  90653. return result;
  90654. };
  90655. /**
  90656. * Creates a MorphTarget from mesh data
  90657. * @param mesh defines the source mesh
  90658. * @param name defines the name to use for the new target
  90659. * @param influence defines the influence to attach to the target
  90660. * @returns a new MorphTarget
  90661. */
  90662. MorphTarget.FromMesh = function (mesh, name, influence) {
  90663. if (!name) {
  90664. name = mesh.name;
  90665. }
  90666. var result = new MorphTarget(name, influence, mesh.getScene());
  90667. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  90668. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90669. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  90670. }
  90671. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  90672. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  90673. }
  90674. return result;
  90675. };
  90676. return MorphTarget;
  90677. }());
  90678. BABYLON.MorphTarget = MorphTarget;
  90679. })(BABYLON || (BABYLON = {}));
  90680. //# sourceMappingURL=babylon.morphTarget.js.map
  90681. var BABYLON;
  90682. (function (BABYLON) {
  90683. /**
  90684. * This class is used to deform meshes using morphing between different targets
  90685. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90686. */
  90687. var MorphTargetManager = /** @class */ (function () {
  90688. /**
  90689. * Creates a new MorphTargetManager
  90690. * @param scene defines the current scene
  90691. */
  90692. function MorphTargetManager(scene) {
  90693. if (scene === void 0) { scene = null; }
  90694. this._targets = new Array();
  90695. this._targetObservable = new Array();
  90696. this._activeTargets = new BABYLON.SmartArray(16);
  90697. this._supportsNormals = false;
  90698. this._supportsTangents = false;
  90699. this._vertexCount = 0;
  90700. this._uniqueId = 0;
  90701. this._tempInfluences = new Array();
  90702. if (!scene) {
  90703. scene = BABYLON.Engine.LastCreatedScene;
  90704. }
  90705. this._scene = scene;
  90706. if (this._scene) {
  90707. this._scene.morphTargetManagers.push(this);
  90708. this._uniqueId = this._scene.getUniqueId();
  90709. }
  90710. }
  90711. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  90712. /**
  90713. * Gets the unique ID of this manager
  90714. */
  90715. get: function () {
  90716. return this._uniqueId;
  90717. },
  90718. enumerable: true,
  90719. configurable: true
  90720. });
  90721. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  90722. /**
  90723. * Gets the number of vertices handled by this manager
  90724. */
  90725. get: function () {
  90726. return this._vertexCount;
  90727. },
  90728. enumerable: true,
  90729. configurable: true
  90730. });
  90731. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  90732. /**
  90733. * Gets a boolean indicating if this manager supports morphing of normals
  90734. */
  90735. get: function () {
  90736. return this._supportsNormals;
  90737. },
  90738. enumerable: true,
  90739. configurable: true
  90740. });
  90741. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  90742. /**
  90743. * Gets a boolean indicating if this manager supports morphing of tangents
  90744. */
  90745. get: function () {
  90746. return this._supportsTangents;
  90747. },
  90748. enumerable: true,
  90749. configurable: true
  90750. });
  90751. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  90752. /**
  90753. * Gets the number of targets stored in this manager
  90754. */
  90755. get: function () {
  90756. return this._targets.length;
  90757. },
  90758. enumerable: true,
  90759. configurable: true
  90760. });
  90761. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  90762. /**
  90763. * Gets the number of influencers (ie. the number of targets with influences > 0)
  90764. */
  90765. get: function () {
  90766. return this._activeTargets.length;
  90767. },
  90768. enumerable: true,
  90769. configurable: true
  90770. });
  90771. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  90772. /**
  90773. * Gets the list of influences (one per target)
  90774. */
  90775. get: function () {
  90776. return this._influences;
  90777. },
  90778. enumerable: true,
  90779. configurable: true
  90780. });
  90781. /**
  90782. * Gets the active target at specified index. An active target is a target with an influence > 0
  90783. * @param index defines the index to check
  90784. * @returns the requested target
  90785. */
  90786. MorphTargetManager.prototype.getActiveTarget = function (index) {
  90787. return this._activeTargets.data[index];
  90788. };
  90789. /**
  90790. * Gets the target at specified index
  90791. * @param index defines the index to check
  90792. * @returns the requested target
  90793. */
  90794. MorphTargetManager.prototype.getTarget = function (index) {
  90795. return this._targets[index];
  90796. };
  90797. /**
  90798. * Add a new target to this manager
  90799. * @param target defines the target to add
  90800. */
  90801. MorphTargetManager.prototype.addTarget = function (target) {
  90802. var _this = this;
  90803. this._targets.push(target);
  90804. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  90805. _this._syncActiveTargets(needUpdate);
  90806. }));
  90807. this._syncActiveTargets(true);
  90808. };
  90809. /**
  90810. * Removes a target from the manager
  90811. * @param target defines the target to remove
  90812. */
  90813. MorphTargetManager.prototype.removeTarget = function (target) {
  90814. var index = this._targets.indexOf(target);
  90815. if (index >= 0) {
  90816. this._targets.splice(index, 1);
  90817. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  90818. this._syncActiveTargets(true);
  90819. }
  90820. };
  90821. /**
  90822. * Serializes the current manager into a Serialization object
  90823. * @returns the serialized object
  90824. */
  90825. MorphTargetManager.prototype.serialize = function () {
  90826. var serializationObject = {};
  90827. serializationObject.id = this.uniqueId;
  90828. serializationObject.targets = [];
  90829. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90830. var target = _a[_i];
  90831. serializationObject.targets.push(target.serialize());
  90832. }
  90833. return serializationObject;
  90834. };
  90835. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  90836. var influenceCount = 0;
  90837. this._activeTargets.reset();
  90838. this._supportsNormals = true;
  90839. this._supportsTangents = true;
  90840. this._vertexCount = 0;
  90841. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90842. var target = _a[_i];
  90843. this._activeTargets.push(target);
  90844. this._tempInfluences[influenceCount++] = target.influence;
  90845. var positions = target.getPositions();
  90846. if (positions) {
  90847. this._supportsNormals = this._supportsNormals && target.hasNormals;
  90848. this._supportsTangents = this._supportsTangents && target.hasTangents;
  90849. var vertexCount = positions.length / 3;
  90850. if (this._vertexCount === 0) {
  90851. this._vertexCount = vertexCount;
  90852. }
  90853. else if (this._vertexCount !== vertexCount) {
  90854. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  90855. return;
  90856. }
  90857. }
  90858. }
  90859. if (!this._influences || this._influences.length !== influenceCount) {
  90860. this._influences = new Float32Array(influenceCount);
  90861. }
  90862. for (var index = 0; index < influenceCount; index++) {
  90863. this._influences[index] = this._tempInfluences[index];
  90864. }
  90865. if (needUpdate) {
  90866. this.synchronize();
  90867. }
  90868. };
  90869. /**
  90870. * Syncrhonize the targets with all the meshes using this morph target manager
  90871. */
  90872. MorphTargetManager.prototype.synchronize = function () {
  90873. if (!this._scene) {
  90874. return;
  90875. }
  90876. // Flag meshes as dirty to resync with the active targets
  90877. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  90878. var mesh = _a[_i];
  90879. if (mesh.morphTargetManager === this) {
  90880. mesh._syncGeometryWithMorphTargetManager();
  90881. }
  90882. }
  90883. };
  90884. // Statics
  90885. /**
  90886. * Creates a new MorphTargetManager from serialized data
  90887. * @param serializationObject defines the serialized data
  90888. * @param scene defines the hosting scene
  90889. * @returns the new MorphTargetManager
  90890. */
  90891. MorphTargetManager.Parse = function (serializationObject, scene) {
  90892. var result = new MorphTargetManager(scene);
  90893. result._uniqueId = serializationObject.id;
  90894. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  90895. var targetData = _a[_i];
  90896. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  90897. }
  90898. return result;
  90899. };
  90900. return MorphTargetManager;
  90901. }());
  90902. BABYLON.MorphTargetManager = MorphTargetManager;
  90903. })(BABYLON || (BABYLON = {}));
  90904. //# sourceMappingURL=babylon.morphTargetManager.js.map
  90905. var BABYLON;
  90906. (function (BABYLON) {
  90907. var Octree = /** @class */ (function () {
  90908. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  90909. if (maxDepth === void 0) { maxDepth = 2; }
  90910. this.maxDepth = maxDepth;
  90911. this.dynamicContent = new Array();
  90912. this._maxBlockCapacity = maxBlockCapacity || 64;
  90913. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  90914. this._creationFunc = creationFunc;
  90915. }
  90916. // Methods
  90917. Octree.prototype.update = function (worldMin, worldMax, entries) {
  90918. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  90919. };
  90920. Octree.prototype.addMesh = function (entry) {
  90921. for (var index = 0; index < this.blocks.length; index++) {
  90922. var block = this.blocks[index];
  90923. block.addEntry(entry);
  90924. }
  90925. };
  90926. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  90927. this._selectionContent.reset();
  90928. for (var index = 0; index < this.blocks.length; index++) {
  90929. var block = this.blocks[index];
  90930. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  90931. }
  90932. if (allowDuplicate) {
  90933. this._selectionContent.concat(this.dynamicContent);
  90934. }
  90935. else {
  90936. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90937. }
  90938. return this._selectionContent;
  90939. };
  90940. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  90941. this._selectionContent.reset();
  90942. for (var index = 0; index < this.blocks.length; index++) {
  90943. var block = this.blocks[index];
  90944. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  90945. }
  90946. if (allowDuplicate) {
  90947. this._selectionContent.concat(this.dynamicContent);
  90948. }
  90949. else {
  90950. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90951. }
  90952. return this._selectionContent;
  90953. };
  90954. Octree.prototype.intersectsRay = function (ray) {
  90955. this._selectionContent.reset();
  90956. for (var index = 0; index < this.blocks.length; index++) {
  90957. var block = this.blocks[index];
  90958. block.intersectsRay(ray, this._selectionContent);
  90959. }
  90960. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90961. return this._selectionContent;
  90962. };
  90963. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  90964. target.blocks = new Array();
  90965. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  90966. // Segmenting space
  90967. for (var x = 0; x < 2; x++) {
  90968. for (var y = 0; y < 2; y++) {
  90969. for (var z = 0; z < 2; z++) {
  90970. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  90971. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  90972. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  90973. block.addEntries(entries);
  90974. target.blocks.push(block);
  90975. }
  90976. }
  90977. }
  90978. };
  90979. Octree.CreationFuncForMeshes = function (entry, block) {
  90980. var boundingInfo = entry.getBoundingInfo();
  90981. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90982. block.entries.push(entry);
  90983. }
  90984. };
  90985. Octree.CreationFuncForSubMeshes = function (entry, block) {
  90986. var boundingInfo = entry.getBoundingInfo();
  90987. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90988. block.entries.push(entry);
  90989. }
  90990. };
  90991. return Octree;
  90992. }());
  90993. BABYLON.Octree = Octree;
  90994. })(BABYLON || (BABYLON = {}));
  90995. //# sourceMappingURL=babylon.octree.js.map
  90996. var BABYLON;
  90997. (function (BABYLON) {
  90998. var OctreeBlock = /** @class */ (function () {
  90999. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  91000. this.entries = new Array();
  91001. this._boundingVectors = new Array();
  91002. this._capacity = capacity;
  91003. this._depth = depth;
  91004. this._maxDepth = maxDepth;
  91005. this._creationFunc = creationFunc;
  91006. this._minPoint = minPoint;
  91007. this._maxPoint = maxPoint;
  91008. this._boundingVectors.push(minPoint.clone());
  91009. this._boundingVectors.push(maxPoint.clone());
  91010. this._boundingVectors.push(minPoint.clone());
  91011. this._boundingVectors[2].x = maxPoint.x;
  91012. this._boundingVectors.push(minPoint.clone());
  91013. this._boundingVectors[3].y = maxPoint.y;
  91014. this._boundingVectors.push(minPoint.clone());
  91015. this._boundingVectors[4].z = maxPoint.z;
  91016. this._boundingVectors.push(maxPoint.clone());
  91017. this._boundingVectors[5].z = minPoint.z;
  91018. this._boundingVectors.push(maxPoint.clone());
  91019. this._boundingVectors[6].x = minPoint.x;
  91020. this._boundingVectors.push(maxPoint.clone());
  91021. this._boundingVectors[7].y = minPoint.y;
  91022. }
  91023. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  91024. // Property
  91025. get: function () {
  91026. return this._capacity;
  91027. },
  91028. enumerable: true,
  91029. configurable: true
  91030. });
  91031. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  91032. get: function () {
  91033. return this._minPoint;
  91034. },
  91035. enumerable: true,
  91036. configurable: true
  91037. });
  91038. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  91039. get: function () {
  91040. return this._maxPoint;
  91041. },
  91042. enumerable: true,
  91043. configurable: true
  91044. });
  91045. // Methods
  91046. OctreeBlock.prototype.addEntry = function (entry) {
  91047. if (this.blocks) {
  91048. for (var index = 0; index < this.blocks.length; index++) {
  91049. var block = this.blocks[index];
  91050. block.addEntry(entry);
  91051. }
  91052. return;
  91053. }
  91054. this._creationFunc(entry, this);
  91055. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  91056. this.createInnerBlocks();
  91057. }
  91058. };
  91059. OctreeBlock.prototype.addEntries = function (entries) {
  91060. for (var index = 0; index < entries.length; index++) {
  91061. var mesh = entries[index];
  91062. this.addEntry(mesh);
  91063. }
  91064. };
  91065. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  91066. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  91067. if (this.blocks) {
  91068. for (var index = 0; index < this.blocks.length; index++) {
  91069. var block = this.blocks[index];
  91070. block.select(frustumPlanes, selection, allowDuplicate);
  91071. }
  91072. return;
  91073. }
  91074. if (allowDuplicate) {
  91075. selection.concat(this.entries);
  91076. }
  91077. else {
  91078. selection.concatWithNoDuplicate(this.entries);
  91079. }
  91080. }
  91081. };
  91082. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  91083. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  91084. if (this.blocks) {
  91085. for (var index = 0; index < this.blocks.length; index++) {
  91086. var block = this.blocks[index];
  91087. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  91088. }
  91089. return;
  91090. }
  91091. if (allowDuplicate) {
  91092. selection.concat(this.entries);
  91093. }
  91094. else {
  91095. selection.concatWithNoDuplicate(this.entries);
  91096. }
  91097. }
  91098. };
  91099. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  91100. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  91101. if (this.blocks) {
  91102. for (var index = 0; index < this.blocks.length; index++) {
  91103. var block = this.blocks[index];
  91104. block.intersectsRay(ray, selection);
  91105. }
  91106. return;
  91107. }
  91108. selection.concatWithNoDuplicate(this.entries);
  91109. }
  91110. };
  91111. OctreeBlock.prototype.createInnerBlocks = function () {
  91112. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  91113. };
  91114. return OctreeBlock;
  91115. }());
  91116. BABYLON.OctreeBlock = OctreeBlock;
  91117. })(BABYLON || (BABYLON = {}));
  91118. //# sourceMappingURL=babylon.octreeBlock.js.map
  91119. var BABYLON;
  91120. (function (BABYLON) {
  91121. /**
  91122. * Postprocess used to generate anaglyphic rendering
  91123. */
  91124. var AnaglyphPostProcess = /** @class */ (function (_super) {
  91125. __extends(AnaglyphPostProcess, _super);
  91126. /**
  91127. * Creates a new AnaglyphPostProcess
  91128. * @param name defines postprocess name
  91129. * @param options defines creation options or target ratio scale
  91130. * @param rigCameras defines cameras using this postprocess
  91131. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  91132. * @param engine defines hosting engine
  91133. * @param reusable defines if the postprocess will be reused multiple times per frame
  91134. */
  91135. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  91136. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  91137. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91138. _this.onApplyObservable.add(function (effect) {
  91139. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  91140. });
  91141. return _this;
  91142. }
  91143. return AnaglyphPostProcess;
  91144. }(BABYLON.PostProcess));
  91145. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  91146. })(BABYLON || (BABYLON = {}));
  91147. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  91148. var BABYLON;
  91149. (function (BABYLON) {
  91150. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  91151. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91152. });
  91153. /**
  91154. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  91155. */
  91156. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  91157. __extends(AnaglyphArcRotateCamera, _super);
  91158. /**
  91159. * Creates a new AnaglyphArcRotateCamera
  91160. * @param name defines camera name
  91161. * @param alpha defines alpha angle (in radians)
  91162. * @param beta defines beta angle (in radians)
  91163. * @param radius defines radius
  91164. * @param target defines camera target
  91165. * @param interaxialDistance defines distance between each color axis
  91166. * @param scene defines the hosting scene
  91167. */
  91168. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  91169. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91170. _this.interaxialDistance = interaxialDistance;
  91171. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91172. return _this;
  91173. }
  91174. /**
  91175. * Gets camera class name
  91176. * @returns AnaglyphArcRotateCamera
  91177. */
  91178. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  91179. return "AnaglyphArcRotateCamera";
  91180. };
  91181. return AnaglyphArcRotateCamera;
  91182. }(BABYLON.ArcRotateCamera));
  91183. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  91184. })(BABYLON || (BABYLON = {}));
  91185. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  91186. var BABYLON;
  91187. (function (BABYLON) {
  91188. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  91189. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91190. });
  91191. /**
  91192. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  91193. */
  91194. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  91195. __extends(AnaglyphFreeCamera, _super);
  91196. /**
  91197. * Creates a new AnaglyphFreeCamera
  91198. * @param name defines camera name
  91199. * @param position defines initial position
  91200. * @param interaxialDistance defines distance between each color axis
  91201. * @param scene defines the hosting scene
  91202. */
  91203. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  91204. var _this = _super.call(this, name, position, scene) || this;
  91205. _this.interaxialDistance = interaxialDistance;
  91206. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91207. return _this;
  91208. }
  91209. /**
  91210. * Gets camera class name
  91211. * @returns AnaglyphFreeCamera
  91212. */
  91213. AnaglyphFreeCamera.prototype.getClassName = function () {
  91214. return "AnaglyphFreeCamera";
  91215. };
  91216. return AnaglyphFreeCamera;
  91217. }(BABYLON.FreeCamera));
  91218. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  91219. })(BABYLON || (BABYLON = {}));
  91220. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  91221. var BABYLON;
  91222. (function (BABYLON) {
  91223. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  91224. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91225. });
  91226. /**
  91227. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  91228. */
  91229. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  91230. __extends(AnaglyphGamepadCamera, _super);
  91231. /**
  91232. * Creates a new AnaglyphGamepadCamera
  91233. * @param name defines camera name
  91234. * @param position defines initial position
  91235. * @param interaxialDistance defines distance between each color axis
  91236. * @param scene defines the hosting scene
  91237. */
  91238. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  91239. var _this = _super.call(this, name, position, scene) || this;
  91240. _this.interaxialDistance = interaxialDistance;
  91241. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91242. return _this;
  91243. }
  91244. /**
  91245. * Gets camera class name
  91246. * @returns AnaglyphGamepadCamera
  91247. */
  91248. AnaglyphGamepadCamera.prototype.getClassName = function () {
  91249. return "AnaglyphGamepadCamera";
  91250. };
  91251. return AnaglyphGamepadCamera;
  91252. }(BABYLON.GamepadCamera));
  91253. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  91254. })(BABYLON || (BABYLON = {}));
  91255. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  91256. var BABYLON;
  91257. (function (BABYLON) {
  91258. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  91259. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91260. });
  91261. /**
  91262. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  91263. */
  91264. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  91265. __extends(AnaglyphUniversalCamera, _super);
  91266. /**
  91267. * Creates a new AnaglyphUniversalCamera
  91268. * @param name defines camera name
  91269. * @param position defines initial position
  91270. * @param interaxialDistance defines distance between each color axis
  91271. * @param scene defines the hosting scene
  91272. */
  91273. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  91274. var _this = _super.call(this, name, position, scene) || this;
  91275. _this.interaxialDistance = interaxialDistance;
  91276. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91277. return _this;
  91278. }
  91279. /**
  91280. * Gets camera class name
  91281. * @returns AnaglyphUniversalCamera
  91282. */
  91283. AnaglyphUniversalCamera.prototype.getClassName = function () {
  91284. return "AnaglyphUniversalCamera";
  91285. };
  91286. return AnaglyphUniversalCamera;
  91287. }(BABYLON.UniversalCamera));
  91288. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  91289. })(BABYLON || (BABYLON = {}));
  91290. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  91291. var BABYLON;
  91292. (function (BABYLON) {
  91293. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  91294. __extends(VRDistortionCorrectionPostProcess, _super);
  91295. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  91296. var _this = _super.call(this, name, "vrDistortionCorrection", [
  91297. 'LensCenter',
  91298. 'Scale',
  91299. 'ScaleIn',
  91300. 'HmdWarpParam'
  91301. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  91302. _this._isRightEye = isRightEye;
  91303. _this._distortionFactors = vrMetrics.distortionK;
  91304. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  91305. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  91306. _this.adaptScaleToCurrentViewport = true;
  91307. _this.onSizeChangedObservable.add(function () {
  91308. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  91309. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  91310. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  91311. });
  91312. _this.onApplyObservable.add(function (effect) {
  91313. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  91314. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  91315. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  91316. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  91317. });
  91318. return _this;
  91319. }
  91320. return VRDistortionCorrectionPostProcess;
  91321. }(BABYLON.PostProcess));
  91322. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  91323. })(BABYLON || (BABYLON = {}));
  91324. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  91325. var BABYLON;
  91326. (function (BABYLON) {
  91327. /**
  91328. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  91329. * Screen rotation is taken into account.
  91330. */
  91331. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  91332. function FreeCameraDeviceOrientationInput() {
  91333. var _this = this;
  91334. this._screenOrientationAngle = 0;
  91335. this._screenQuaternion = new BABYLON.Quaternion();
  91336. this._alpha = 0;
  91337. this._beta = 0;
  91338. this._gamma = 0;
  91339. this._orientationChanged = function () {
  91340. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  91341. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  91342. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  91343. };
  91344. this._deviceOrientation = function (evt) {
  91345. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  91346. _this._beta = evt.beta !== null ? evt.beta : 0;
  91347. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  91348. };
  91349. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  91350. this._orientationChanged();
  91351. }
  91352. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  91353. get: function () {
  91354. return this._camera;
  91355. },
  91356. set: function (camera) {
  91357. this._camera = camera;
  91358. if (this._camera != null && !this._camera.rotationQuaternion) {
  91359. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  91360. }
  91361. },
  91362. enumerable: true,
  91363. configurable: true
  91364. });
  91365. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91366. window.addEventListener("orientationchange", this._orientationChanged);
  91367. window.addEventListener("deviceorientation", this._deviceOrientation);
  91368. //In certain cases, the attach control is called AFTER orientation was changed,
  91369. //So this is needed.
  91370. this._orientationChanged();
  91371. };
  91372. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  91373. window.removeEventListener("orientationchange", this._orientationChanged);
  91374. window.removeEventListener("deviceorientation", this._deviceOrientation);
  91375. };
  91376. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  91377. //if no device orientation provided, don't update the rotation.
  91378. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  91379. if (!this._alpha)
  91380. return;
  91381. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  91382. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  91383. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  91384. //Mirror on XY Plane
  91385. this._camera.rotationQuaternion.z *= -1;
  91386. this._camera.rotationQuaternion.w *= -1;
  91387. };
  91388. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  91389. return "FreeCameraDeviceOrientationInput";
  91390. };
  91391. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  91392. return "deviceOrientation";
  91393. };
  91394. return FreeCameraDeviceOrientationInput;
  91395. }());
  91396. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  91397. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  91398. })(BABYLON || (BABYLON = {}));
  91399. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  91400. var BABYLON;
  91401. (function (BABYLON) {
  91402. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  91403. function ArcRotateCameraVRDeviceOrientationInput() {
  91404. this.alphaCorrection = 1;
  91405. this.betaCorrection = 1;
  91406. this.gammaCorrection = 1;
  91407. this._alpha = 0;
  91408. this._gamma = 0;
  91409. this._dirty = false;
  91410. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  91411. }
  91412. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91413. this.camera.attachControl(element, noPreventDefault);
  91414. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  91415. };
  91416. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  91417. if (evt.alpha !== null) {
  91418. this._alpha = +evt.alpha | 0;
  91419. }
  91420. if (evt.gamma !== null) {
  91421. this._gamma = +evt.gamma | 0;
  91422. }
  91423. this._dirty = true;
  91424. };
  91425. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  91426. if (this._dirty) {
  91427. this._dirty = false;
  91428. if (this._gamma < 0) {
  91429. this._gamma = 180 + this._gamma;
  91430. }
  91431. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  91432. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  91433. }
  91434. };
  91435. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  91436. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  91437. };
  91438. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  91439. return "ArcRotateCameraVRDeviceOrientationInput";
  91440. };
  91441. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  91442. return "VRDeviceOrientation";
  91443. };
  91444. return ArcRotateCameraVRDeviceOrientationInput;
  91445. }());
  91446. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  91447. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  91448. })(BABYLON || (BABYLON = {}));
  91449. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  91450. var BABYLON;
  91451. (function (BABYLON) {
  91452. var VRCameraMetrics = /** @class */ (function () {
  91453. function VRCameraMetrics() {
  91454. this.compensateDistortion = true;
  91455. }
  91456. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  91457. get: function () {
  91458. return this.hResolution / (2 * this.vResolution);
  91459. },
  91460. enumerable: true,
  91461. configurable: true
  91462. });
  91463. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  91464. get: function () {
  91465. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  91466. },
  91467. enumerable: true,
  91468. configurable: true
  91469. });
  91470. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  91471. get: function () {
  91472. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91473. var h = (4 * meters) / this.hScreenSize;
  91474. return BABYLON.Matrix.Translation(h, 0, 0);
  91475. },
  91476. enumerable: true,
  91477. configurable: true
  91478. });
  91479. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  91480. get: function () {
  91481. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91482. var h = (4 * meters) / this.hScreenSize;
  91483. return BABYLON.Matrix.Translation(-h, 0, 0);
  91484. },
  91485. enumerable: true,
  91486. configurable: true
  91487. });
  91488. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  91489. get: function () {
  91490. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  91491. },
  91492. enumerable: true,
  91493. configurable: true
  91494. });
  91495. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  91496. get: function () {
  91497. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  91498. },
  91499. enumerable: true,
  91500. configurable: true
  91501. });
  91502. VRCameraMetrics.GetDefault = function () {
  91503. var result = new VRCameraMetrics();
  91504. result.hResolution = 1280;
  91505. result.vResolution = 800;
  91506. result.hScreenSize = 0.149759993;
  91507. result.vScreenSize = 0.0935999975;
  91508. result.vScreenCenter = 0.0467999987;
  91509. result.eyeToScreenDistance = 0.0410000011;
  91510. result.lensSeparationDistance = 0.0635000020;
  91511. result.interpupillaryDistance = 0.0640000030;
  91512. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  91513. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  91514. result.postProcessScaleFactor = 1.714605507808412;
  91515. result.lensCenterOffset = 0.151976421;
  91516. return result;
  91517. };
  91518. return VRCameraMetrics;
  91519. }());
  91520. BABYLON.VRCameraMetrics = VRCameraMetrics;
  91521. })(BABYLON || (BABYLON = {}));
  91522. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  91523. var BABYLON;
  91524. (function (BABYLON) {
  91525. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  91526. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  91527. });
  91528. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  91529. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  91530. });
  91531. /**
  91532. * This represents a WebVR camera.
  91533. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  91534. * @example http://doc.babylonjs.com/how_to/webvr_camera
  91535. */
  91536. var WebVRFreeCamera = /** @class */ (function (_super) {
  91537. __extends(WebVRFreeCamera, _super);
  91538. /**
  91539. * Instantiates a WebVRFreeCamera.
  91540. * @param name The name of the WebVRFreeCamera
  91541. * @param position The starting anchor position for the camera
  91542. * @param scene The scene the camera belongs to
  91543. * @param webVROptions a set of customizable options for the webVRCamera
  91544. */
  91545. function WebVRFreeCamera(name, position, scene, webVROptions) {
  91546. if (webVROptions === void 0) { webVROptions = {}; }
  91547. var _this = _super.call(this, name, position, scene) || this;
  91548. _this.webVROptions = webVROptions;
  91549. /**
  91550. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  91551. */
  91552. _this._vrDevice = null;
  91553. /**
  91554. * The rawPose of the vrDevice.
  91555. */
  91556. _this.rawPose = null;
  91557. _this._specsVersion = "1.1";
  91558. _this._attached = false;
  91559. _this._descendants = [];
  91560. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  91561. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  91562. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  91563. _this._standingMatrix = null;
  91564. /**
  91565. * Represents device position in babylon space.
  91566. */
  91567. _this.devicePosition = BABYLON.Vector3.Zero();
  91568. /**
  91569. * Represents device rotation in babylon space.
  91570. */
  91571. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  91572. /**
  91573. * The scale of the device to be used when translating from device space to babylon space.
  91574. */
  91575. _this.deviceScaleFactor = 1;
  91576. _this._deviceToWorld = BABYLON.Matrix.Identity();
  91577. _this._worldToDevice = BABYLON.Matrix.Identity();
  91578. /**
  91579. * References to the webVR controllers for the vrDevice.
  91580. */
  91581. _this.controllers = [];
  91582. /**
  91583. * Emits an event when a controller is attached.
  91584. */
  91585. _this.onControllersAttachedObservable = new BABYLON.Observable();
  91586. /**
  91587. * Emits an event when a controller's mesh has been loaded;
  91588. */
  91589. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  91590. /**
  91591. * If the rig cameras be used as parent instead of this camera.
  91592. */
  91593. _this.rigParenting = true;
  91594. _this._defaultHeight = undefined;
  91595. _this._workingVector = BABYLON.Vector3.Zero();
  91596. _this._oneVector = BABYLON.Vector3.One();
  91597. _this._workingMatrix = BABYLON.Matrix.Identity();
  91598. _this._cache.position = BABYLON.Vector3.Zero();
  91599. if (webVROptions.defaultHeight) {
  91600. _this._defaultHeight = webVROptions.defaultHeight;
  91601. _this.position.y = _this._defaultHeight;
  91602. }
  91603. _this.minZ = 0.1;
  91604. //legacy support - the compensation boolean was removed.
  91605. if (arguments.length === 5) {
  91606. _this.webVROptions = arguments[4];
  91607. }
  91608. // default webVR options
  91609. if (_this.webVROptions.trackPosition == undefined) {
  91610. _this.webVROptions.trackPosition = true;
  91611. }
  91612. if (_this.webVROptions.controllerMeshes == undefined) {
  91613. _this.webVROptions.controllerMeshes = true;
  91614. }
  91615. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  91616. _this.webVROptions.defaultLightingOnControllers = true;
  91617. }
  91618. _this.rotationQuaternion = new BABYLON.Quaternion();
  91619. if (_this.webVROptions && _this.webVROptions.positionScale) {
  91620. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  91621. }
  91622. //enable VR
  91623. var engine = _this.getEngine();
  91624. _this._onVREnabled = function (success) { if (success) {
  91625. _this.initControllers();
  91626. } };
  91627. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  91628. engine.initWebVR().add(function (event) {
  91629. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  91630. return;
  91631. }
  91632. _this._vrDevice = event.vrDisplay;
  91633. //reset the rig parameters.
  91634. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  91635. if (_this._attached) {
  91636. _this.getEngine().enableVR();
  91637. }
  91638. });
  91639. if (typeof (VRFrameData) !== "undefined")
  91640. _this._frameData = new VRFrameData();
  91641. /**
  91642. * The idea behind the following lines:
  91643. * objects that have the camera as parent should actually have the rig cameras as a parent.
  91644. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  91645. * the second will not show it correctly.
  91646. *
  91647. * To solve this - each object that has the camera as parent will be added to a protected array.
  91648. * When the rig camera renders, it will take this array and set all of those to be its children.
  91649. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  91650. * Amazing!
  91651. */
  91652. scene.onBeforeCameraRenderObservable.add(function (camera) {
  91653. if (camera.parent === _this && _this.rigParenting) {
  91654. _this._descendants = _this.getDescendants(true, function (n) {
  91655. // don't take the cameras or the controllers!
  91656. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  91657. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  91658. return !isController && !isRigCamera;
  91659. });
  91660. _this._descendants.forEach(function (node) {
  91661. node.parent = camera;
  91662. });
  91663. }
  91664. });
  91665. scene.onAfterCameraRenderObservable.add(function (camera) {
  91666. if (camera.parent === _this && _this.rigParenting) {
  91667. _this._descendants.forEach(function (node) {
  91668. node.parent = _this;
  91669. });
  91670. }
  91671. });
  91672. return _this;
  91673. }
  91674. /**
  91675. * Gets the device distance from the ground in meters.
  91676. * @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.
  91677. */
  91678. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  91679. if (this._standingMatrix) {
  91680. // Add standing matrix offset to get real offset from ground in room
  91681. this._standingMatrix.getTranslationToRef(this._workingVector);
  91682. return this._deviceRoomPosition.y + this._workingVector.y;
  91683. }
  91684. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  91685. return this._defaultHeight || 0;
  91686. };
  91687. /**
  91688. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91689. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  91690. */
  91691. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  91692. var _this = this;
  91693. if (callback === void 0) { callback = function (bool) { }; }
  91694. // Use standing matrix if available
  91695. this.getEngine().initWebVRAsync().then(function (result) {
  91696. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  91697. callback(false);
  91698. }
  91699. else {
  91700. _this._standingMatrix = new BABYLON.Matrix();
  91701. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  91702. if (!_this.getScene().useRightHandedSystem) {
  91703. [2, 6, 8, 9, 14].forEach(function (num) {
  91704. if (_this._standingMatrix) {
  91705. _this._standingMatrix.m[num] *= -1;
  91706. }
  91707. });
  91708. }
  91709. callback(true);
  91710. }
  91711. });
  91712. };
  91713. /**
  91714. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91715. * @returns A promise with a boolean set to if the standing matrix is supported.
  91716. */
  91717. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  91718. var _this = this;
  91719. return new Promise(function (res, rej) {
  91720. _this.useStandingMatrix(function (supported) {
  91721. res(supported);
  91722. });
  91723. });
  91724. };
  91725. /**
  91726. * Disposes the camera
  91727. */
  91728. WebVRFreeCamera.prototype.dispose = function () {
  91729. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  91730. _super.prototype.dispose.call(this);
  91731. };
  91732. /**
  91733. * Gets a vrController by name.
  91734. * @param name The name of the controller to retreive
  91735. * @returns the controller matching the name specified or null if not found
  91736. */
  91737. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  91738. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  91739. var gp = _a[_i];
  91740. if (gp.hand === name) {
  91741. return gp;
  91742. }
  91743. }
  91744. return null;
  91745. };
  91746. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  91747. /**
  91748. * The controller corrisponding to the users left hand.
  91749. */
  91750. get: function () {
  91751. if (!this._leftController) {
  91752. this._leftController = this.getControllerByName("left");
  91753. }
  91754. return this._leftController;
  91755. },
  91756. enumerable: true,
  91757. configurable: true
  91758. });
  91759. ;
  91760. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  91761. /**
  91762. * The controller corrisponding to the users right hand.
  91763. */
  91764. get: function () {
  91765. if (!this._rightController) {
  91766. this._rightController = this.getControllerByName("right");
  91767. }
  91768. return this._rightController;
  91769. },
  91770. enumerable: true,
  91771. configurable: true
  91772. });
  91773. ;
  91774. /**
  91775. * Casts a ray forward from the vrCamera's gaze.
  91776. * @param length Length of the ray (default: 100)
  91777. * @returns the ray corrisponding to the gaze
  91778. */
  91779. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  91780. if (length === void 0) { length = 100; }
  91781. if (this.leftCamera) {
  91782. // Use left eye to avoid computation to compute center on every call
  91783. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  91784. }
  91785. else {
  91786. return _super.prototype.getForwardRay.call(this, length);
  91787. }
  91788. };
  91789. /**
  91790. * Updates the camera based on device's frame data
  91791. */
  91792. WebVRFreeCamera.prototype._checkInputs = function () {
  91793. if (this._vrDevice && this._vrDevice.isPresenting) {
  91794. this._vrDevice.getFrameData(this._frameData);
  91795. this.updateFromDevice(this._frameData.pose);
  91796. }
  91797. _super.prototype._checkInputs.call(this);
  91798. };
  91799. /**
  91800. * Updates the poseControlled values based on the input device pose.
  91801. * @param poseData Pose coming from the device
  91802. */
  91803. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  91804. if (poseData && poseData.orientation) {
  91805. this.rawPose = poseData;
  91806. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  91807. if (this.getScene().useRightHandedSystem) {
  91808. this._deviceRoomRotationQuaternion.z *= -1;
  91809. this._deviceRoomRotationQuaternion.w *= -1;
  91810. }
  91811. if (this.webVROptions.trackPosition && this.rawPose.position) {
  91812. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  91813. if (this.getScene().useRightHandedSystem) {
  91814. this._deviceRoomPosition.z *= -1;
  91815. }
  91816. }
  91817. }
  91818. };
  91819. /**
  91820. * WebVR's attach control will start broadcasting frames to the device.
  91821. * Note that in certain browsers (chrome for example) this function must be called
  91822. * within a user-interaction callback. Example:
  91823. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  91824. *
  91825. * @param element html element to attach the vrDevice to
  91826. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  91827. */
  91828. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  91829. _super.prototype.attachControl.call(this, element, noPreventDefault);
  91830. this._attached = true;
  91831. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  91832. if (this._vrDevice) {
  91833. this.getEngine().enableVR();
  91834. }
  91835. };
  91836. /**
  91837. * Detaches the camera from the html element and disables VR
  91838. *
  91839. * @param element html element to detach from
  91840. */
  91841. WebVRFreeCamera.prototype.detachControl = function (element) {
  91842. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  91843. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  91844. _super.prototype.detachControl.call(this, element);
  91845. this._attached = false;
  91846. this.getEngine().disableVR();
  91847. };
  91848. /**
  91849. * @returns the name of this class
  91850. */
  91851. WebVRFreeCamera.prototype.getClassName = function () {
  91852. return "WebVRFreeCamera";
  91853. };
  91854. /**
  91855. * Calls resetPose on the vrDisplay
  91856. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  91857. */
  91858. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  91859. //uses the vrDisplay's "resetPose()".
  91860. //pitch and roll won't be affected.
  91861. this._vrDevice.resetPose();
  91862. };
  91863. /**
  91864. * Updates the rig cameras (left and right eye)
  91865. */
  91866. WebVRFreeCamera.prototype._updateRigCameras = function () {
  91867. var camLeft = this._rigCameras[0];
  91868. var camRight = this._rigCameras[1];
  91869. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91870. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91871. camLeft.position.copyFrom(this._deviceRoomPosition);
  91872. camRight.position.copyFrom(this._deviceRoomPosition);
  91873. };
  91874. /**
  91875. * Updates the cached values of the camera
  91876. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  91877. */
  91878. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  91879. var _this = this;
  91880. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  91881. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  91882. if (!this.updateCacheCalled) {
  91883. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  91884. this.updateCacheCalled = true;
  91885. this.update();
  91886. }
  91887. // Set working vector to the device position in room space rotated by the new rotation
  91888. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  91889. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  91890. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  91891. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  91892. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  91893. // Add translation from anchor position
  91894. this._deviceToWorld.getTranslationToRef(this._workingVector);
  91895. this._workingVector.addInPlace(this.position);
  91896. this._workingVector.subtractInPlace(this._cache.position);
  91897. this._deviceToWorld.setTranslation(this._workingVector);
  91898. // Set an inverted matrix to be used when updating the camera
  91899. this._deviceToWorld.invertToRef(this._worldToDevice);
  91900. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  91901. this.controllers.forEach(function (controller) {
  91902. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  91903. controller.update();
  91904. });
  91905. }
  91906. if (!ignoreParentClass) {
  91907. _super.prototype._updateCache.call(this);
  91908. }
  91909. this.updateCacheCalled = false;
  91910. };
  91911. /**
  91912. * Updates the current device position and rotation in the babylon world
  91913. */
  91914. WebVRFreeCamera.prototype.update = function () {
  91915. // Get current device position in babylon world
  91916. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  91917. // Get current device rotation in babylon world
  91918. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  91919. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  91920. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  91921. _super.prototype.update.call(this);
  91922. };
  91923. /**
  91924. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  91925. * @returns an identity matrix
  91926. */
  91927. WebVRFreeCamera.prototype._getViewMatrix = function () {
  91928. return BABYLON.Matrix.Identity();
  91929. };
  91930. /**
  91931. * This function is called by the two RIG cameras.
  91932. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  91933. */
  91934. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  91935. var _this = this;
  91936. // Update the parent camera prior to using a child camera to avoid desynchronization
  91937. var parentCamera = this._cameraRigParams["parentCamera"];
  91938. parentCamera._updateCache();
  91939. //WebVR 1.1
  91940. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  91941. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  91942. if (!this.getScene().useRightHandedSystem) {
  91943. [2, 6, 8, 9, 14].forEach(function (num) {
  91944. _this._webvrViewMatrix.m[num] *= -1;
  91945. });
  91946. }
  91947. // update the camera rotation matrix
  91948. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  91949. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  91950. // Computing target and final matrix
  91951. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  91952. // should the view matrix be updated with scale and position offset?
  91953. if (parentCamera.deviceScaleFactor !== 1) {
  91954. this._webvrViewMatrix.invert();
  91955. // scale the position, if set
  91956. if (parentCamera.deviceScaleFactor) {
  91957. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  91958. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  91959. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  91960. }
  91961. this._webvrViewMatrix.invert();
  91962. }
  91963. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  91964. // Compute global position
  91965. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  91966. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  91967. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  91968. this._workingMatrix.getTranslationToRef(this._globalPosition);
  91969. this._markSyncedWithParent();
  91970. return this._webvrViewMatrix;
  91971. };
  91972. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  91973. var _this = this;
  91974. var parentCamera = this.parent;
  91975. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  91976. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  91977. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  91978. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  91979. //babylon compatible matrix
  91980. if (!this.getScene().useRightHandedSystem) {
  91981. [8, 9, 10, 11].forEach(function (num) {
  91982. _this._projectionMatrix.m[num] *= -1;
  91983. });
  91984. }
  91985. return this._projectionMatrix;
  91986. };
  91987. /**
  91988. * Initializes the controllers and their meshes
  91989. */
  91990. WebVRFreeCamera.prototype.initControllers = function () {
  91991. var _this = this;
  91992. this.controllers = [];
  91993. var manager = this.getScene().gamepadManager;
  91994. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  91995. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91996. var webVrController = gamepad;
  91997. if (webVrController.defaultModel) {
  91998. webVrController.defaultModel.setEnabled(false);
  91999. }
  92000. if (webVrController.hand === "right") {
  92001. _this._rightController = null;
  92002. }
  92003. if (webVrController.hand === "left") {
  92004. _this._leftController = null;
  92005. }
  92006. var controllerIndex = _this.controllers.indexOf(webVrController);
  92007. if (controllerIndex !== -1) {
  92008. _this.controllers.splice(controllerIndex, 1);
  92009. }
  92010. }
  92011. });
  92012. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  92013. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  92014. var webVrController_1 = gamepad;
  92015. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  92016. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  92017. if (_this.webVROptions.controllerMeshes) {
  92018. if (webVrController_1.defaultModel) {
  92019. webVrController_1.defaultModel.setEnabled(true);
  92020. }
  92021. else {
  92022. // Load the meshes
  92023. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  92024. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  92025. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  92026. if (_this.webVROptions.defaultLightingOnControllers) {
  92027. if (!_this._lightOnControllers) {
  92028. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  92029. }
  92030. var activateLightOnSubMeshes_1 = function (mesh, light) {
  92031. var children = mesh.getChildren();
  92032. if (children.length !== 0) {
  92033. children.forEach(function (mesh) {
  92034. light.includedOnlyMeshes.push(mesh);
  92035. activateLightOnSubMeshes_1(mesh, light);
  92036. });
  92037. }
  92038. };
  92039. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  92040. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  92041. }
  92042. });
  92043. }
  92044. }
  92045. webVrController_1.attachToPoseControlledCamera(_this);
  92046. // since this is async - sanity check. Is the controller already stored?
  92047. if (_this.controllers.indexOf(webVrController_1) === -1) {
  92048. //add to the controllers array
  92049. _this.controllers.push(webVrController_1);
  92050. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  92051. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  92052. // So we're overriding setting left & right manually to be sure
  92053. var firstViveWandDetected = false;
  92054. for (var i = 0; i < _this.controllers.length; i++) {
  92055. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  92056. if (!firstViveWandDetected) {
  92057. firstViveWandDetected = true;
  92058. _this.controllers[i].hand = "left";
  92059. }
  92060. else {
  92061. _this.controllers[i].hand = "right";
  92062. }
  92063. }
  92064. }
  92065. //did we find enough controllers? Great! let the developer know.
  92066. if (_this.controllers.length >= 2) {
  92067. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  92068. }
  92069. }
  92070. }
  92071. });
  92072. };
  92073. return WebVRFreeCamera;
  92074. }(BABYLON.FreeCamera));
  92075. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  92076. })(BABYLON || (BABYLON = {}));
  92077. //# sourceMappingURL=babylon.webVRCamera.js.map
  92078. var BABYLON;
  92079. (function (BABYLON) {
  92080. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  92081. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  92082. });
  92083. // We're mainly based on the logic defined into the FreeCamera code
  92084. /**
  92085. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  92086. * being tilted forward or back and left or right.
  92087. */
  92088. var DeviceOrientationCamera = /** @class */ (function (_super) {
  92089. __extends(DeviceOrientationCamera, _super);
  92090. /**
  92091. * Creates a new device orientation camera
  92092. * @param name The name of the camera
  92093. * @param position The start position camera
  92094. * @param scene The scene the camera belongs to
  92095. */
  92096. function DeviceOrientationCamera(name, position, scene) {
  92097. var _this = _super.call(this, name, position, scene) || this;
  92098. _this._quaternionCache = new BABYLON.Quaternion();
  92099. _this.inputs.addDeviceOrientation();
  92100. return _this;
  92101. }
  92102. /**
  92103. * Gets the current instance class name ("DeviceOrientationCamera").
  92104. * This helps avoiding instanceof at run time.
  92105. * @returns the class name
  92106. */
  92107. DeviceOrientationCamera.prototype.getClassName = function () {
  92108. return "DeviceOrientationCamera";
  92109. };
  92110. /**
  92111. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  92112. */
  92113. DeviceOrientationCamera.prototype._checkInputs = function () {
  92114. _super.prototype._checkInputs.call(this);
  92115. this._quaternionCache.copyFrom(this.rotationQuaternion);
  92116. if (this._initialQuaternion) {
  92117. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  92118. }
  92119. };
  92120. /**
  92121. * Reset the camera to its default orientation on the specified axis only.
  92122. * @param axis The axis to reset
  92123. */
  92124. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  92125. var _this = this;
  92126. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  92127. //can only work if this camera has a rotation quaternion already.
  92128. if (!this.rotationQuaternion)
  92129. return;
  92130. if (!this._initialQuaternion) {
  92131. this._initialQuaternion = new BABYLON.Quaternion();
  92132. }
  92133. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  92134. ['x', 'y', 'z'].forEach(function (axisName) {
  92135. if (!axis[axisName]) {
  92136. _this._initialQuaternion[axisName] = 0;
  92137. }
  92138. else {
  92139. _this._initialQuaternion[axisName] *= -1;
  92140. }
  92141. });
  92142. this._initialQuaternion.normalize();
  92143. //force rotation update
  92144. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  92145. };
  92146. return DeviceOrientationCamera;
  92147. }(BABYLON.FreeCamera));
  92148. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  92149. })(BABYLON || (BABYLON = {}));
  92150. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  92151. var BABYLON;
  92152. (function (BABYLON) {
  92153. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  92154. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92155. });
  92156. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  92157. __extends(VRDeviceOrientationFreeCamera, _super);
  92158. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  92159. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92160. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92161. var _this = _super.call(this, name, position, scene) || this;
  92162. vrCameraMetrics.compensateDistortion = compensateDistortion;
  92163. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  92164. return _this;
  92165. }
  92166. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  92167. return "VRDeviceOrientationFreeCamera";
  92168. };
  92169. return VRDeviceOrientationFreeCamera;
  92170. }(BABYLON.DeviceOrientationCamera));
  92171. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  92172. })(BABYLON || (BABYLON = {}));
  92173. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  92174. var BABYLON;
  92175. (function (BABYLON) {
  92176. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  92177. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  92178. });
  92179. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  92180. __extends(VRDeviceOrientationArcRotateCamera, _super);
  92181. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  92182. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92183. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92184. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92185. vrCameraMetrics.compensateDistortion = compensateDistortion;
  92186. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  92187. _this.inputs.addVRDeviceOrientation();
  92188. return _this;
  92189. }
  92190. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  92191. return "VRDeviceOrientationArcRotateCamera";
  92192. };
  92193. return VRDeviceOrientationArcRotateCamera;
  92194. }(BABYLON.ArcRotateCamera));
  92195. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  92196. })(BABYLON || (BABYLON = {}));
  92197. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  92198. var BABYLON;
  92199. (function (BABYLON) {
  92200. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  92201. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  92202. });
  92203. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  92204. __extends(VRDeviceOrientationGamepadCamera, _super);
  92205. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  92206. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92207. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92208. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  92209. _this.inputs.addGamepad();
  92210. return _this;
  92211. }
  92212. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  92213. return "VRDeviceOrientationGamepadCamera";
  92214. };
  92215. return VRDeviceOrientationGamepadCamera;
  92216. }(BABYLON.VRDeviceOrientationFreeCamera));
  92217. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  92218. })(BABYLON || (BABYLON = {}));
  92219. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  92220. var BABYLON;
  92221. (function (BABYLON) {
  92222. var VRExperienceHelperGazer = /** @class */ (function () {
  92223. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  92224. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  92225. this.scene = scene;
  92226. this._pointerDownOnMeshAsked = false;
  92227. this._isActionableMesh = false;
  92228. this._teleportationRequestInitiated = false;
  92229. this._teleportationBackRequestInitiated = false;
  92230. this._rotationRightAsked = false;
  92231. this._rotationLeftAsked = false;
  92232. this._dpadPressed = true;
  92233. this._activePointer = false;
  92234. this._id = VRExperienceHelperGazer._idCounter++;
  92235. // Gaze tracker
  92236. if (!gazeTrackerToClone) {
  92237. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  92238. this._gazeTracker.bakeCurrentTransformIntoVertices();
  92239. this._gazeTracker.isPickable = false;
  92240. this._gazeTracker.isVisible = false;
  92241. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  92242. targetMat.specularColor = BABYLON.Color3.Black();
  92243. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92244. targetMat.backFaceCulling = false;
  92245. this._gazeTracker.material = targetMat;
  92246. }
  92247. else {
  92248. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  92249. }
  92250. }
  92251. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  92252. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  92253. };
  92254. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  92255. this._pointerDownOnMeshAsked = true;
  92256. if (this._currentHit) {
  92257. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  92258. }
  92259. };
  92260. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  92261. if (this._currentHit) {
  92262. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  92263. }
  92264. this._pointerDownOnMeshAsked = false;
  92265. };
  92266. VRExperienceHelperGazer.prototype._activatePointer = function () {
  92267. this._activePointer = true;
  92268. };
  92269. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  92270. this._activePointer = false;
  92271. };
  92272. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  92273. if (distance === void 0) { distance = 100; }
  92274. };
  92275. VRExperienceHelperGazer.prototype.dispose = function () {
  92276. this._interactionsEnabled = false;
  92277. this._teleportationEnabled = false;
  92278. if (this._gazeTracker) {
  92279. this._gazeTracker.dispose();
  92280. }
  92281. };
  92282. VRExperienceHelperGazer._idCounter = 0;
  92283. return VRExperienceHelperGazer;
  92284. }());
  92285. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  92286. __extends(VRExperienceHelperControllerGazer, _super);
  92287. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  92288. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  92289. _this.webVRController = webVRController;
  92290. // Laser pointer
  92291. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  92292. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  92293. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92294. laserPointerMaterial.alpha = 0.6;
  92295. _this._laserPointer.material = laserPointerMaterial;
  92296. _this._laserPointer.rotation.x = Math.PI / 2;
  92297. _this._laserPointer.position.z = -0.5;
  92298. _this._laserPointer.isVisible = false;
  92299. _this._laserPointer.isPickable = false;
  92300. if (!webVRController.mesh) {
  92301. // Create an empty mesh that is used prior to loading the high quality model
  92302. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  92303. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  92304. preloadPointerPose.rotation.x = -0.7;
  92305. preloadMesh.addChild(preloadPointerPose);
  92306. webVRController.attachToMesh(preloadMesh);
  92307. }
  92308. _this._setLaserPointerParent(webVRController.mesh);
  92309. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  92310. _this._setLaserPointerParent(mesh);
  92311. });
  92312. return _this;
  92313. }
  92314. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  92315. return this.webVRController.getForwardRay(length);
  92316. };
  92317. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  92318. _super.prototype._activatePointer.call(this);
  92319. this._laserPointer.isVisible = true;
  92320. };
  92321. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  92322. _super.prototype._deactivatePointer.call(this);
  92323. this._laserPointer.isVisible = false;
  92324. };
  92325. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  92326. this._laserPointer.material.emissiveColor = color;
  92327. };
  92328. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  92329. var makeNotPick = function (root) {
  92330. root.name += " laserPointer";
  92331. root.isPickable = false;
  92332. root.getChildMeshes().forEach(function (c) {
  92333. makeNotPick(c);
  92334. });
  92335. };
  92336. makeNotPick(mesh);
  92337. var childMeshes = mesh.getChildMeshes();
  92338. this.webVRController._pointingPoseNode = null;
  92339. for (var i = 0; i < childMeshes.length; i++) {
  92340. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  92341. mesh = childMeshes[i];
  92342. this.webVRController._pointingPoseNode = mesh;
  92343. break;
  92344. }
  92345. }
  92346. this._laserPointer.parent = mesh;
  92347. };
  92348. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  92349. if (distance === void 0) { distance = 100; }
  92350. this._laserPointer.scaling.y = distance;
  92351. this._laserPointer.position.z = -distance / 2;
  92352. };
  92353. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  92354. _super.prototype.dispose.call(this);
  92355. this._laserPointer.dispose();
  92356. if (this._meshAttachedObserver) {
  92357. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  92358. }
  92359. };
  92360. return VRExperienceHelperControllerGazer;
  92361. }(VRExperienceHelperGazer));
  92362. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  92363. __extends(VRExperienceHelperCameraGazer, _super);
  92364. function VRExperienceHelperCameraGazer(getCamera, scene) {
  92365. var _this = _super.call(this, scene) || this;
  92366. _this.getCamera = getCamera;
  92367. return _this;
  92368. }
  92369. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  92370. var camera = this.getCamera();
  92371. if (camera) {
  92372. return camera.getForwardRay(length);
  92373. }
  92374. else {
  92375. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  92376. }
  92377. };
  92378. return VRExperienceHelperCameraGazer;
  92379. }(VRExperienceHelperGazer));
  92380. /**
  92381. * Helps to quickly add VR support to an existing scene.
  92382. * See http://doc.babylonjs.com/how_to/webvr_helper
  92383. */
  92384. var VRExperienceHelper = /** @class */ (function () {
  92385. /**
  92386. * Instantiates a VRExperienceHelper.
  92387. * Helps to quickly add VR support to an existing scene.
  92388. * @param scene The scene the VRExperienceHelper belongs to.
  92389. * @param webVROptions Options to modify the vr experience helper's behavior.
  92390. */
  92391. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  92392. if (webVROptions === void 0) { webVROptions = {}; }
  92393. var _this = this;
  92394. this.webVROptions = webVROptions;
  92395. // Can the system support WebVR, even if a headset isn't plugged in?
  92396. this._webVRsupported = false;
  92397. // If WebVR is supported, is a headset plugged in and are we ready to present?
  92398. this._webVRready = false;
  92399. // Are we waiting for the requestPresent callback to complete?
  92400. this._webVRrequesting = false;
  92401. // Are we presenting to the headset right now?
  92402. this._webVRpresenting = false;
  92403. // Are we presenting in the fullscreen fallback?
  92404. this._fullscreenVRpresenting = false;
  92405. /**
  92406. * Observable raised when entering VR.
  92407. */
  92408. this.onEnteringVRObservable = new BABYLON.Observable();
  92409. /**
  92410. * Observable raised when exiting VR.
  92411. */
  92412. this.onExitingVRObservable = new BABYLON.Observable();
  92413. /**
  92414. * Observable raised when controller mesh is loaded.
  92415. */
  92416. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92417. this._useCustomVRButton = false;
  92418. this._teleportationRequested = false;
  92419. this._teleportActive = false;
  92420. this._floorMeshesCollection = [];
  92421. this._rotationAllowed = true;
  92422. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  92423. this._isDefaultTeleportationTarget = true;
  92424. this._teleportationFillColor = "#444444";
  92425. this._teleportationBorderColor = "#FFFFFF";
  92426. this._rotationAngle = 0;
  92427. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  92428. this._padSensibilityUp = 0.65;
  92429. this._padSensibilityDown = 0.35;
  92430. this.leftController = null;
  92431. this.rightController = null;
  92432. /**
  92433. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  92434. */
  92435. this.onNewMeshSelected = new BABYLON.Observable();
  92436. /**
  92437. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  92438. */
  92439. this.onNewMeshPicked = new BABYLON.Observable();
  92440. /**
  92441. * Observable raised before camera teleportation
  92442. */
  92443. this.onBeforeCameraTeleport = new BABYLON.Observable();
  92444. /**
  92445. * Observable raised after camera teleportation
  92446. */
  92447. this.onAfterCameraTeleport = new BABYLON.Observable();
  92448. /**
  92449. * Observable raised when current selected mesh gets unselected
  92450. */
  92451. this.onSelectedMeshUnselected = new BABYLON.Observable();
  92452. /**
  92453. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  92454. */
  92455. this.teleportationEnabled = true;
  92456. this._teleportationInitialized = false;
  92457. this._interactionsEnabled = false;
  92458. this._interactionsRequested = false;
  92459. this._displayGaze = true;
  92460. this._displayLaserPointer = true;
  92461. this._onResize = function () {
  92462. _this.moveButtonToBottomRight();
  92463. if (_this._fullscreenVRpresenting && _this._webVRready) {
  92464. _this.exitVR();
  92465. }
  92466. };
  92467. this._onFullscreenChange = function () {
  92468. if (document.fullscreen !== undefined) {
  92469. _this._fullscreenVRpresenting = document.fullscreen;
  92470. }
  92471. else if (document.mozFullScreen !== undefined) {
  92472. _this._fullscreenVRpresenting = document.mozFullScreen;
  92473. }
  92474. else if (document.webkitIsFullScreen !== undefined) {
  92475. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  92476. }
  92477. else if (document.msIsFullScreen !== undefined) {
  92478. _this._fullscreenVRpresenting = document.msIsFullScreen;
  92479. }
  92480. else if (document.msFullscreenElement !== undefined) {
  92481. _this._fullscreenVRpresenting = document.msFullscreenElement;
  92482. }
  92483. if (!_this._fullscreenVRpresenting && _this._canvas) {
  92484. _this.exitVR();
  92485. if (!_this._useCustomVRButton) {
  92486. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  92487. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  92488. }
  92489. }
  92490. };
  92491. this.beforeRender = function () {
  92492. if (_this.leftController && _this.leftController._activePointer) {
  92493. _this._castRayAndSelectObject(_this.leftController);
  92494. }
  92495. if (_this.rightController && _this.rightController._activePointer) {
  92496. _this._castRayAndSelectObject(_this.rightController);
  92497. }
  92498. if (_this._noControllerIsActive) {
  92499. _this._castRayAndSelectObject(_this._cameraGazer);
  92500. }
  92501. else {
  92502. _this._cameraGazer._gazeTracker.isVisible = false;
  92503. }
  92504. };
  92505. this._onNewGamepadConnected = function (gamepad) {
  92506. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  92507. if (gamepad.leftStick) {
  92508. gamepad.onleftstickchanged(function (stickValues) {
  92509. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  92510. // Listening to classic/xbox gamepad only if no VR controller is active
  92511. if ((!_this.leftController && !_this.rightController) ||
  92512. ((_this.leftController && !_this.leftController._activePointer) &&
  92513. (_this.rightController && !_this.rightController._activePointer))) {
  92514. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  92515. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  92516. }
  92517. }
  92518. });
  92519. }
  92520. if (gamepad.rightStick) {
  92521. gamepad.onrightstickchanged(function (stickValues) {
  92522. if (_this._teleportationInitialized) {
  92523. _this._checkRotate(stickValues, _this._cameraGazer);
  92524. }
  92525. });
  92526. }
  92527. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  92528. gamepad.onbuttondown(function (buttonPressed) {
  92529. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92530. _this._cameraGazer._selectionPointerDown();
  92531. }
  92532. });
  92533. gamepad.onbuttonup(function (buttonPressed) {
  92534. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92535. _this._cameraGazer._selectionPointerUp();
  92536. }
  92537. });
  92538. }
  92539. }
  92540. else {
  92541. var webVRController = gamepad;
  92542. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  92543. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  92544. _this.rightController = controller;
  92545. }
  92546. else {
  92547. _this.leftController = controller;
  92548. }
  92549. _this._tryEnableInteractionOnController(controller);
  92550. }
  92551. };
  92552. // 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
  92553. this._tryEnableInteractionOnController = function (controller) {
  92554. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  92555. _this._enableInteractionOnController(controller);
  92556. }
  92557. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  92558. _this._enableTeleportationOnController(controller);
  92559. }
  92560. };
  92561. this._onNewGamepadDisconnected = function (gamepad) {
  92562. if (gamepad instanceof BABYLON.WebVRController) {
  92563. if (gamepad.hand === "left" && _this.leftController != null) {
  92564. _this.leftController.dispose();
  92565. _this.leftController = null;
  92566. }
  92567. if (gamepad.hand === "right" && _this.rightController != null) {
  92568. _this.rightController.dispose();
  92569. _this.rightController = null;
  92570. }
  92571. }
  92572. };
  92573. this._workingVector = BABYLON.Vector3.Zero();
  92574. this._workingQuaternion = BABYLON.Quaternion.Identity();
  92575. this._workingMatrix = BABYLON.Matrix.Identity();
  92576. this._scene = scene;
  92577. this._canvas = scene.getEngine().getRenderingCanvas();
  92578. // Parse options
  92579. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  92580. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  92581. }
  92582. if (webVROptions.createDeviceOrientationCamera === undefined) {
  92583. webVROptions.createDeviceOrientationCamera = true;
  92584. }
  92585. if (webVROptions.laserToggle === undefined) {
  92586. webVROptions.laserToggle = true;
  92587. }
  92588. if (webVROptions.defaultHeight === undefined) {
  92589. webVROptions.defaultHeight = 1.7;
  92590. }
  92591. if (webVROptions.useCustomVRButton) {
  92592. this._useCustomVRButton = true;
  92593. if (webVROptions.customVRButton) {
  92594. this._btnVR = webVROptions.customVRButton;
  92595. }
  92596. }
  92597. if (webVROptions.rayLength) {
  92598. this._rayLength = webVROptions.rayLength;
  92599. }
  92600. this._defaultHeight = webVROptions.defaultHeight;
  92601. if (webVROptions.positionScale) {
  92602. this._rayLength *= webVROptions.positionScale;
  92603. this._defaultHeight *= webVROptions.positionScale;
  92604. }
  92605. // Set position
  92606. if (this._scene.activeCamera) {
  92607. this._position = this._scene.activeCamera.position.clone();
  92608. }
  92609. else {
  92610. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  92611. }
  92612. // Set non-vr camera
  92613. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  92614. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  92615. // Copy data from existing camera
  92616. if (this._scene.activeCamera) {
  92617. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92618. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  92619. // Set rotation from previous camera
  92620. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  92621. var targetCamera = this._scene.activeCamera;
  92622. if (targetCamera.rotationQuaternion) {
  92623. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  92624. }
  92625. else {
  92626. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  92627. }
  92628. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  92629. }
  92630. }
  92631. this._scene.activeCamera = this._deviceOrientationCamera;
  92632. if (this._canvas) {
  92633. this._scene.activeCamera.attachControl(this._canvas);
  92634. }
  92635. }
  92636. else {
  92637. this._existingCamera = this._scene.activeCamera;
  92638. }
  92639. // Create VR cameras
  92640. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92641. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  92642. }
  92643. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  92644. this._webVRCamera.useStandingMatrix();
  92645. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  92646. // Create default button
  92647. if (!this._useCustomVRButton) {
  92648. this._btnVR = document.createElement("BUTTON");
  92649. this._btnVR.className = "babylonVRicon";
  92650. this._btnVR.id = "babylonVRiconbtn";
  92651. this._btnVR.title = "Click to switch to VR";
  92652. 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) }";
  92653. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  92654. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  92655. // css += ".babylonVRicon.vrdisplaysupported { }";
  92656. // css += ".babylonVRicon.vrdisplayready { }";
  92657. // css += ".babylonVRicon.vrdisplayrequesting { }";
  92658. var style = document.createElement('style');
  92659. style.appendChild(document.createTextNode(css));
  92660. document.getElementsByTagName('head')[0].appendChild(style);
  92661. this.moveButtonToBottomRight();
  92662. }
  92663. // VR button click event
  92664. if (this._btnVR) {
  92665. this._btnVR.addEventListener("click", function () {
  92666. if (!_this.isInVRMode) {
  92667. _this.enterVR();
  92668. }
  92669. else {
  92670. _this.exitVR();
  92671. }
  92672. });
  92673. }
  92674. // Window events
  92675. window.addEventListener("resize", this._onResize);
  92676. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  92677. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  92678. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  92679. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  92680. document.onmsfullscreenchange = this._onFullscreenChange;
  92681. // Display vr button when headset is connected
  92682. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92683. this.displayVRButton();
  92684. }
  92685. else {
  92686. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  92687. if (e.vrDisplay) {
  92688. _this.displayVRButton();
  92689. }
  92690. });
  92691. }
  92692. // Exiting VR mode using 'ESC' key on desktop
  92693. this._onKeyDown = function (event) {
  92694. if (event.keyCode === 27 && _this.isInVRMode) {
  92695. _this.exitVR();
  92696. }
  92697. };
  92698. document.addEventListener("keydown", this._onKeyDown);
  92699. // Exiting VR mode double tapping the touch screen
  92700. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  92701. if (_this.isInVRMode) {
  92702. _this.exitVR();
  92703. if (_this._fullscreenVRpresenting) {
  92704. _this._scene.getEngine().switchFullscreen(true);
  92705. }
  92706. }
  92707. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  92708. // Listen for WebVR display changes
  92709. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  92710. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  92711. this._onVRRequestPresentStart = function () {
  92712. _this._webVRrequesting = true;
  92713. _this.updateButtonVisibility();
  92714. };
  92715. this._onVRRequestPresentComplete = function (success) {
  92716. _this._webVRrequesting = false;
  92717. _this.updateButtonVisibility();
  92718. };
  92719. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  92720. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  92721. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  92722. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92723. scene.onDisposeObservable.add(function () {
  92724. _this.dispose();
  92725. });
  92726. // Gamepad connection events
  92727. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  92728. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  92729. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  92730. this.updateButtonVisibility();
  92731. //create easing functions
  92732. this._circleEase = new BABYLON.CircleEase();
  92733. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92734. if (this.webVROptions.floorMeshes) {
  92735. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  92736. }
  92737. }
  92738. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  92739. /** Return this.onEnteringVRObservable
  92740. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  92741. */
  92742. get: function () {
  92743. return this.onEnteringVRObservable;
  92744. },
  92745. enumerable: true,
  92746. configurable: true
  92747. });
  92748. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  92749. /** Return this.onExitingVRObservable
  92750. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  92751. */
  92752. get: function () {
  92753. return this.onExitingVRObservable;
  92754. },
  92755. enumerable: true,
  92756. configurable: true
  92757. });
  92758. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  92759. /** Return this.onControllerMeshLoadedObservable
  92760. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  92761. */
  92762. get: function () {
  92763. return this.onControllerMeshLoadedObservable;
  92764. },
  92765. enumerable: true,
  92766. configurable: true
  92767. });
  92768. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  92769. /**
  92770. * The mesh used to display where the user is going to teleport.
  92771. */
  92772. get: function () {
  92773. return this._teleportationTarget;
  92774. },
  92775. /**
  92776. * Sets the mesh to be used to display where the user is going to teleport.
  92777. */
  92778. set: function (value) {
  92779. if (value) {
  92780. value.name = "teleportationTarget";
  92781. this._isDefaultTeleportationTarget = false;
  92782. this._teleportationTarget = value;
  92783. }
  92784. },
  92785. enumerable: true,
  92786. configurable: true
  92787. });
  92788. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  92789. /**
  92790. * The mesh used to display where the user is selecting,
  92791. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  92792. * See http://doc.babylonjs.com/resources/baking_transformations
  92793. */
  92794. get: function () {
  92795. return this._cameraGazer._gazeTracker;
  92796. },
  92797. set: function (value) {
  92798. if (value) {
  92799. this._cameraGazer._gazeTracker = value;
  92800. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  92801. this._cameraGazer._gazeTracker.isPickable = false;
  92802. this._cameraGazer._gazeTracker.isVisible = false;
  92803. this._cameraGazer._gazeTracker.name = "gazeTracker";
  92804. if (this.leftController) {
  92805. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92806. }
  92807. if (this.rightController) {
  92808. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92809. }
  92810. }
  92811. },
  92812. enumerable: true,
  92813. configurable: true
  92814. });
  92815. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  92816. /**
  92817. * If the ray of the gaze should be displayed.
  92818. */
  92819. get: function () {
  92820. return this._displayGaze;
  92821. },
  92822. /**
  92823. * Sets if the ray of the gaze should be displayed.
  92824. */
  92825. set: function (value) {
  92826. this._displayGaze = value;
  92827. if (!value) {
  92828. this._cameraGazer._gazeTracker.isVisible = false;
  92829. if (this.leftController) {
  92830. this.leftController._gazeTracker.isVisible = false;
  92831. }
  92832. if (this.rightController) {
  92833. this.rightController._gazeTracker.isVisible = false;
  92834. }
  92835. }
  92836. },
  92837. enumerable: true,
  92838. configurable: true
  92839. });
  92840. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  92841. /**
  92842. * If the ray of the LaserPointer should be displayed.
  92843. */
  92844. get: function () {
  92845. return this._displayLaserPointer;
  92846. },
  92847. /**
  92848. * Sets if the ray of the LaserPointer should be displayed.
  92849. */
  92850. set: function (value) {
  92851. this._displayLaserPointer = value;
  92852. if (!value) {
  92853. if (this.rightController) {
  92854. this.rightController._deactivatePointer();
  92855. this.rightController._gazeTracker.isVisible = false;
  92856. }
  92857. if (this.leftController) {
  92858. this.leftController._deactivatePointer();
  92859. this.leftController._gazeTracker.isVisible = false;
  92860. }
  92861. }
  92862. else {
  92863. if (this.rightController) {
  92864. this.rightController._activatePointer();
  92865. }
  92866. if (this.leftController) {
  92867. this.leftController._activatePointer();
  92868. }
  92869. }
  92870. },
  92871. enumerable: true,
  92872. configurable: true
  92873. });
  92874. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  92875. /**
  92876. * The deviceOrientationCamera used as the camera when not in VR.
  92877. */
  92878. get: function () {
  92879. return this._deviceOrientationCamera;
  92880. },
  92881. enumerable: true,
  92882. configurable: true
  92883. });
  92884. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  92885. /**
  92886. * Based on the current WebVR support, returns the current VR camera used.
  92887. */
  92888. get: function () {
  92889. if (this._webVRready) {
  92890. return this._webVRCamera;
  92891. }
  92892. else {
  92893. return this._scene.activeCamera;
  92894. }
  92895. },
  92896. enumerable: true,
  92897. configurable: true
  92898. });
  92899. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  92900. /**
  92901. * The webVRCamera which is used when in VR.
  92902. */
  92903. get: function () {
  92904. return this._webVRCamera;
  92905. },
  92906. enumerable: true,
  92907. configurable: true
  92908. });
  92909. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  92910. /**
  92911. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  92912. */
  92913. get: function () {
  92914. return this._vrDeviceOrientationCamera;
  92915. },
  92916. enumerable: true,
  92917. configurable: true
  92918. });
  92919. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  92920. get: function () {
  92921. var result = this._cameraGazer._teleportationRequestInitiated
  92922. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  92923. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  92924. return result;
  92925. },
  92926. enumerable: true,
  92927. configurable: true
  92928. });
  92929. // Raised when one of the controller has loaded successfully its associated default mesh
  92930. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  92931. if (this.leftController && this.leftController.webVRController == webVRController) {
  92932. if (webVRController.mesh) {
  92933. this.leftController._setLaserPointerParent(webVRController.mesh);
  92934. }
  92935. }
  92936. if (this.rightController && this.rightController.webVRController == webVRController) {
  92937. if (webVRController.mesh) {
  92938. this.rightController._setLaserPointerParent(webVRController.mesh);
  92939. }
  92940. }
  92941. try {
  92942. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  92943. }
  92944. catch (err) {
  92945. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  92946. }
  92947. };
  92948. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  92949. /**
  92950. * Gets a value indicating if we are currently in VR mode.
  92951. */
  92952. get: function () {
  92953. return this._webVRpresenting || this._fullscreenVRpresenting;
  92954. },
  92955. enumerable: true,
  92956. configurable: true
  92957. });
  92958. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  92959. var vrDisplay = this._scene.getEngine().getVRDevice();
  92960. if (vrDisplay) {
  92961. var wasPresenting = this._webVRpresenting;
  92962. // A VR display is connected
  92963. this._webVRpresenting = vrDisplay.isPresenting;
  92964. if (wasPresenting && !this._webVRpresenting)
  92965. this.exitVR();
  92966. }
  92967. else {
  92968. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  92969. }
  92970. this.updateButtonVisibility();
  92971. };
  92972. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  92973. this._webVRsupported = eventArgs.vrSupported;
  92974. this._webVRready = !!eventArgs.vrDisplay;
  92975. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  92976. this.updateButtonVisibility();
  92977. };
  92978. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  92979. if (this._canvas && !this._useCustomVRButton) {
  92980. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  92981. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  92982. }
  92983. };
  92984. VRExperienceHelper.prototype.displayVRButton = function () {
  92985. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  92986. document.body.appendChild(this._btnVR);
  92987. this._btnVRDisplayed = true;
  92988. }
  92989. };
  92990. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  92991. if (!this._btnVR || this._useCustomVRButton) {
  92992. return;
  92993. }
  92994. this._btnVR.className = "babylonVRicon";
  92995. if (this.isInVRMode) {
  92996. this._btnVR.className += " vrdisplaypresenting";
  92997. }
  92998. else {
  92999. if (this._webVRready)
  93000. this._btnVR.className += " vrdisplayready";
  93001. if (this._webVRsupported)
  93002. this._btnVR.className += " vrdisplaysupported";
  93003. if (this._webVRrequesting)
  93004. this._btnVR.className += " vrdisplayrequesting";
  93005. }
  93006. };
  93007. /**
  93008. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  93009. * Otherwise, will use the fullscreen API.
  93010. */
  93011. VRExperienceHelper.prototype.enterVR = function () {
  93012. if (this.onEnteringVRObservable) {
  93013. try {
  93014. this.onEnteringVRObservable.notifyObservers(this);
  93015. }
  93016. catch (err) {
  93017. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  93018. }
  93019. }
  93020. if (this._scene.activeCamera) {
  93021. this._position = this._scene.activeCamera.position.clone();
  93022. // make sure that we return to the last active camera
  93023. this._existingCamera = this._scene.activeCamera;
  93024. }
  93025. if (this._webVRrequesting)
  93026. return;
  93027. // If WebVR is supported and a headset is connected
  93028. if (this._webVRready) {
  93029. if (!this._webVRpresenting) {
  93030. this._webVRCamera.position = this._position;
  93031. this._scene.activeCamera = this._webVRCamera;
  93032. }
  93033. }
  93034. else if (this._vrDeviceOrientationCamera) {
  93035. this._vrDeviceOrientationCamera.position = this._position;
  93036. if (this._scene.activeCamera) {
  93037. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  93038. }
  93039. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  93040. this._scene.getEngine().switchFullscreen(true);
  93041. this.updateButtonVisibility();
  93042. }
  93043. if (this._scene.activeCamera && this._canvas) {
  93044. this._scene.activeCamera.attachControl(this._canvas);
  93045. }
  93046. if (this._interactionsEnabled) {
  93047. this._scene.registerBeforeRender(this.beforeRender);
  93048. }
  93049. };
  93050. /**
  93051. * Attempt to exit VR, or fullscreen.
  93052. */
  93053. VRExperienceHelper.prototype.exitVR = function () {
  93054. if (this.onExitingVRObservable) {
  93055. try {
  93056. this.onExitingVRObservable.notifyObservers(this);
  93057. }
  93058. catch (err) {
  93059. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  93060. }
  93061. }
  93062. if (this._webVRpresenting) {
  93063. this._scene.getEngine().disableVR();
  93064. }
  93065. if (this._scene.activeCamera) {
  93066. this._position = this._scene.activeCamera.position.clone();
  93067. }
  93068. if (this._deviceOrientationCamera) {
  93069. this._deviceOrientationCamera.position = this._position;
  93070. this._scene.activeCamera = this._deviceOrientationCamera;
  93071. if (this._canvas) {
  93072. this._scene.activeCamera.attachControl(this._canvas);
  93073. }
  93074. }
  93075. else if (this._existingCamera) {
  93076. this._existingCamera.position = this._position;
  93077. this._scene.activeCamera = this._existingCamera;
  93078. }
  93079. this.updateButtonVisibility();
  93080. if (this._interactionsEnabled) {
  93081. this._scene.unregisterBeforeRender(this.beforeRender);
  93082. }
  93083. // resize to update width and height when exiting vr exits fullscreen
  93084. this._scene.getEngine().resize();
  93085. };
  93086. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  93087. /**
  93088. * The position of the vr experience helper.
  93089. */
  93090. get: function () {
  93091. return this._position;
  93092. },
  93093. /**
  93094. * Sets the position of the vr experience helper.
  93095. */
  93096. set: function (value) {
  93097. this._position = value;
  93098. if (this._scene.activeCamera) {
  93099. this._scene.activeCamera.position = value;
  93100. }
  93101. },
  93102. enumerable: true,
  93103. configurable: true
  93104. });
  93105. /**
  93106. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  93107. */
  93108. VRExperienceHelper.prototype.enableInteractions = function () {
  93109. var _this = this;
  93110. if (!this._interactionsEnabled) {
  93111. this._interactionsRequested = true;
  93112. if (this.leftController) {
  93113. this._enableInteractionOnController(this.leftController);
  93114. }
  93115. if (this.rightController) {
  93116. this._enableInteractionOnController(this.rightController);
  93117. }
  93118. this.raySelectionPredicate = function (mesh) {
  93119. return mesh.isVisible;
  93120. };
  93121. this.meshSelectionPredicate = function (mesh) {
  93122. return true;
  93123. };
  93124. this._raySelectionPredicate = function (mesh) {
  93125. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  93126. && mesh.name.indexOf("teleportationTarget") === -1
  93127. && mesh.name.indexOf("torusTeleportation") === -1
  93128. && mesh.name.indexOf("laserPointer") === -1)) {
  93129. return _this.raySelectionPredicate(mesh);
  93130. }
  93131. return false;
  93132. };
  93133. this._interactionsEnabled = true;
  93134. }
  93135. };
  93136. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  93137. get: function () {
  93138. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  93139. },
  93140. enumerable: true,
  93141. configurable: true
  93142. });
  93143. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  93144. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  93145. if (this._floorMeshesCollection[i].id === mesh.id) {
  93146. return true;
  93147. }
  93148. }
  93149. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  93150. return true;
  93151. }
  93152. return false;
  93153. };
  93154. /**
  93155. * Adds a floor mesh to be used for teleportation.
  93156. * @param floorMesh the mesh to be used for teleportation.
  93157. */
  93158. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  93159. if (!this._floorMeshesCollection) {
  93160. return;
  93161. }
  93162. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  93163. return;
  93164. }
  93165. this._floorMeshesCollection.push(floorMesh);
  93166. };
  93167. /**
  93168. * Removes a floor mesh from being used for teleportation.
  93169. * @param floorMesh the mesh to be removed.
  93170. */
  93171. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  93172. if (!this._floorMeshesCollection) {
  93173. return;
  93174. }
  93175. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  93176. if (meshIndex !== -1) {
  93177. this._floorMeshesCollection.splice(meshIndex, 1);
  93178. }
  93179. };
  93180. /**
  93181. * Enables interactions and teleportation using the VR controllers and gaze.
  93182. * @param vrTeleportationOptions options to modify teleportation behavior.
  93183. */
  93184. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  93185. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  93186. if (!this._teleportationInitialized) {
  93187. this._teleportationRequested = true;
  93188. this.enableInteractions();
  93189. if (vrTeleportationOptions.floorMeshName) {
  93190. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  93191. }
  93192. if (vrTeleportationOptions.floorMeshes) {
  93193. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  93194. }
  93195. if (this.leftController != null) {
  93196. this._enableTeleportationOnController(this.leftController);
  93197. }
  93198. if (this.rightController != null) {
  93199. this._enableTeleportationOnController(this.rightController);
  93200. }
  93201. // Creates an image processing post process for the vignette not relying
  93202. // on the main scene configuration for image processing to reduce setup and spaces
  93203. // (gamma/linear) conflicts.
  93204. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  93205. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  93206. imageProcessingConfiguration.vignetteEnabled = true;
  93207. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  93208. this._webVRCamera.detachPostProcess(this._postProcessMove);
  93209. this._teleportationInitialized = true;
  93210. if (this._isDefaultTeleportationTarget) {
  93211. this._createTeleportationCircles();
  93212. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  93213. }
  93214. }
  93215. };
  93216. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  93217. var _this = this;
  93218. var controllerMesh = controller.webVRController.mesh;
  93219. if (controllerMesh) {
  93220. controller._interactionsEnabled = true;
  93221. controller._activatePointer();
  93222. if (this.webVROptions.laserToggle) {
  93223. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  93224. // Enabling / disabling laserPointer
  93225. if (_this._displayLaserPointer && stateObject.value === 1) {
  93226. if (controller._activePointer) {
  93227. controller._deactivatePointer();
  93228. }
  93229. else {
  93230. controller._activatePointer();
  93231. }
  93232. if (_this.displayGaze) {
  93233. controller._gazeTracker.isVisible = controller._activePointer;
  93234. }
  93235. }
  93236. });
  93237. }
  93238. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  93239. var gazer = controller;
  93240. if (_this._noControllerIsActive) {
  93241. gazer = _this._cameraGazer;
  93242. }
  93243. if (!gazer._pointerDownOnMeshAsked) {
  93244. if (stateObject.value > _this._padSensibilityUp) {
  93245. gazer._selectionPointerDown();
  93246. }
  93247. }
  93248. else if (stateObject.value < _this._padSensibilityDown) {
  93249. gazer._selectionPointerUp();
  93250. }
  93251. });
  93252. }
  93253. };
  93254. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  93255. // Dont teleport if another gaze already requested teleportation
  93256. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  93257. return;
  93258. }
  93259. if (!gazer._teleportationRequestInitiated) {
  93260. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  93261. gazer._activatePointer();
  93262. gazer._teleportationRequestInitiated = true;
  93263. }
  93264. }
  93265. else {
  93266. // Listening to the proper controller values changes to confirm teleportation
  93267. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  93268. if (this._teleportActive) {
  93269. this._teleportCamera(this._haloCenter);
  93270. }
  93271. gazer._teleportationRequestInitiated = false;
  93272. }
  93273. }
  93274. };
  93275. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  93276. // Only rotate when user is not currently selecting a teleportation location
  93277. if (gazer._teleportationRequestInitiated) {
  93278. return;
  93279. }
  93280. if (!gazer._rotationLeftAsked) {
  93281. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  93282. gazer._rotationLeftAsked = true;
  93283. if (this._rotationAllowed) {
  93284. this._rotateCamera(false);
  93285. }
  93286. }
  93287. }
  93288. else {
  93289. if (stateObject.x > -this._padSensibilityDown) {
  93290. gazer._rotationLeftAsked = false;
  93291. }
  93292. }
  93293. if (!gazer._rotationRightAsked) {
  93294. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  93295. gazer._rotationRightAsked = true;
  93296. if (this._rotationAllowed) {
  93297. this._rotateCamera(true);
  93298. }
  93299. }
  93300. }
  93301. else {
  93302. if (stateObject.x < this._padSensibilityDown) {
  93303. gazer._rotationRightAsked = false;
  93304. }
  93305. }
  93306. };
  93307. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  93308. // Only teleport backwards when user is not currently selecting a teleportation location
  93309. if (gazer._teleportationRequestInitiated) {
  93310. return;
  93311. }
  93312. // Teleport backwards
  93313. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  93314. if (!gazer._teleportationBackRequestInitiated) {
  93315. if (!this.currentVRCamera) {
  93316. return;
  93317. }
  93318. // Get rotation and position of the current camera
  93319. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  93320. var position = this.currentVRCamera.position;
  93321. // If the camera has device position, use that instead
  93322. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  93323. rotation = this.currentVRCamera.deviceRotationQuaternion;
  93324. position = this.currentVRCamera.devicePosition;
  93325. }
  93326. // Get matrix with only the y rotation of the device rotation
  93327. rotation.toEulerAnglesToRef(this._workingVector);
  93328. this._workingVector.z = 0;
  93329. this._workingVector.x = 0;
  93330. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  93331. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  93332. // Rotate backwards ray by device rotation to cast at the ground behind the user
  93333. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  93334. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  93335. var ray = new BABYLON.Ray(position, this._workingVector);
  93336. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93337. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  93338. this._teleportCamera(hit.pickedPoint);
  93339. }
  93340. gazer._teleportationBackRequestInitiated = true;
  93341. }
  93342. }
  93343. else {
  93344. gazer._teleportationBackRequestInitiated = false;
  93345. }
  93346. };
  93347. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  93348. var _this = this;
  93349. var controllerMesh = controller.webVRController.mesh;
  93350. if (controllerMesh) {
  93351. if (!controller._interactionsEnabled) {
  93352. this._enableInteractionOnController(controller);
  93353. }
  93354. controller._interactionsEnabled = true;
  93355. controller._teleportationEnabled = true;
  93356. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  93357. controller._dpadPressed = false;
  93358. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  93359. controller._dpadPressed = stateObject.pressed;
  93360. if (!controller._dpadPressed) {
  93361. controller._rotationLeftAsked = false;
  93362. controller._rotationRightAsked = false;
  93363. controller._teleportationBackRequestInitiated = false;
  93364. }
  93365. });
  93366. }
  93367. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  93368. if (_this.teleportationEnabled) {
  93369. _this._checkTeleportBackwards(stateObject, controller);
  93370. _this._checkTeleportWithRay(stateObject, controller);
  93371. }
  93372. _this._checkRotate(stateObject, controller);
  93373. });
  93374. }
  93375. };
  93376. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  93377. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  93378. this._teleportationTarget.isPickable = false;
  93379. var length = 512;
  93380. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  93381. dynamicTexture.hasAlpha = true;
  93382. var context = dynamicTexture.getContext();
  93383. var centerX = length / 2;
  93384. var centerY = length / 2;
  93385. var radius = 200;
  93386. context.beginPath();
  93387. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  93388. context.fillStyle = this._teleportationFillColor;
  93389. context.fill();
  93390. context.lineWidth = 10;
  93391. context.strokeStyle = this._teleportationBorderColor;
  93392. context.stroke();
  93393. context.closePath();
  93394. dynamicTexture.update();
  93395. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  93396. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  93397. this._teleportationTarget.material = teleportationCircleMaterial;
  93398. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  93399. torus.isPickable = false;
  93400. torus.parent = this._teleportationTarget;
  93401. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  93402. var keys = [];
  93403. keys.push({
  93404. frame: 0,
  93405. value: 0
  93406. });
  93407. keys.push({
  93408. frame: 30,
  93409. value: 0.4
  93410. });
  93411. keys.push({
  93412. frame: 60,
  93413. value: 0
  93414. });
  93415. animationInnerCircle.setKeys(keys);
  93416. var easingFunction = new BABYLON.SineEase();
  93417. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93418. animationInnerCircle.setEasingFunction(easingFunction);
  93419. torus.animations = [];
  93420. torus.animations.push(animationInnerCircle);
  93421. this._scene.beginAnimation(torus, 0, 60, true);
  93422. this._hideTeleportationTarget();
  93423. };
  93424. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  93425. this._teleportActive = true;
  93426. if (this._teleportationInitialized) {
  93427. this._teleportationTarget.isVisible = true;
  93428. if (this._isDefaultTeleportationTarget) {
  93429. this._teleportationTarget.getChildren()[0].isVisible = true;
  93430. }
  93431. }
  93432. };
  93433. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  93434. this._teleportActive = false;
  93435. if (this._teleportationInitialized) {
  93436. this._teleportationTarget.isVisible = false;
  93437. if (this._isDefaultTeleportationTarget) {
  93438. this._teleportationTarget.getChildren()[0].isVisible = false;
  93439. }
  93440. }
  93441. };
  93442. VRExperienceHelper.prototype._rotateCamera = function (right) {
  93443. var _this = this;
  93444. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93445. return;
  93446. }
  93447. if (right) {
  93448. this._rotationAngle++;
  93449. }
  93450. else {
  93451. this._rotationAngle--;
  93452. }
  93453. this.currentVRCamera.animations = [];
  93454. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  93455. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93456. var animationRotationKeys = [];
  93457. animationRotationKeys.push({
  93458. frame: 0,
  93459. value: this.currentVRCamera.rotationQuaternion
  93460. });
  93461. animationRotationKeys.push({
  93462. frame: 6,
  93463. value: target
  93464. });
  93465. animationRotation.setKeys(animationRotationKeys);
  93466. animationRotation.setEasingFunction(this._circleEase);
  93467. this.currentVRCamera.animations.push(animationRotation);
  93468. this._postProcessMove.animations = [];
  93469. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93470. var vignetteWeightKeys = [];
  93471. vignetteWeightKeys.push({
  93472. frame: 0,
  93473. value: 0
  93474. });
  93475. vignetteWeightKeys.push({
  93476. frame: 3,
  93477. value: 4
  93478. });
  93479. vignetteWeightKeys.push({
  93480. frame: 6,
  93481. value: 0
  93482. });
  93483. animationPP.setKeys(vignetteWeightKeys);
  93484. animationPP.setEasingFunction(this._circleEase);
  93485. this._postProcessMove.animations.push(animationPP);
  93486. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93487. var vignetteStretchKeys = [];
  93488. vignetteStretchKeys.push({
  93489. frame: 0,
  93490. value: 0
  93491. });
  93492. vignetteStretchKeys.push({
  93493. frame: 3,
  93494. value: 10
  93495. });
  93496. vignetteStretchKeys.push({
  93497. frame: 6,
  93498. value: 0
  93499. });
  93500. animationPP2.setKeys(vignetteStretchKeys);
  93501. animationPP2.setEasingFunction(this._circleEase);
  93502. this._postProcessMove.animations.push(animationPP2);
  93503. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93504. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93505. this._postProcessMove.samples = 4;
  93506. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93507. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  93508. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93509. });
  93510. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  93511. };
  93512. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  93513. if (hit.pickedPoint) {
  93514. if (gazer._teleportationRequestInitiated) {
  93515. this._displayTeleportationTarget();
  93516. this._haloCenter.copyFrom(hit.pickedPoint);
  93517. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  93518. }
  93519. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  93520. if (pickNormal) {
  93521. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93522. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93523. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  93524. }
  93525. this._teleportationTarget.position.y += 0.1;
  93526. }
  93527. };
  93528. VRExperienceHelper.prototype._teleportCamera = function (location) {
  93529. var _this = this;
  93530. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93531. return;
  93532. }
  93533. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  93534. // offset of the headset from the anchor.
  93535. if (this.webVRCamera.leftCamera) {
  93536. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  93537. this._workingVector.subtractInPlace(this.webVRCamera.position);
  93538. location.subtractToRef(this._workingVector, this._workingVector);
  93539. }
  93540. else {
  93541. this._workingVector.copyFrom(location);
  93542. }
  93543. // Add height to account for user's height offset
  93544. if (this.isInVRMode) {
  93545. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  93546. }
  93547. else {
  93548. this._workingVector.y += this._defaultHeight;
  93549. }
  93550. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  93551. // Create animation from the camera's position to the new location
  93552. this.currentVRCamera.animations = [];
  93553. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93554. var animationCameraTeleportationKeys = [{
  93555. frame: 0,
  93556. value: this.currentVRCamera.position
  93557. },
  93558. {
  93559. frame: 11,
  93560. value: this._workingVector
  93561. }
  93562. ];
  93563. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  93564. animationCameraTeleportation.setEasingFunction(this._circleEase);
  93565. this.currentVRCamera.animations.push(animationCameraTeleportation);
  93566. this._postProcessMove.animations = [];
  93567. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93568. var vignetteWeightKeys = [];
  93569. vignetteWeightKeys.push({
  93570. frame: 0,
  93571. value: 0
  93572. });
  93573. vignetteWeightKeys.push({
  93574. frame: 5,
  93575. value: 8
  93576. });
  93577. vignetteWeightKeys.push({
  93578. frame: 11,
  93579. value: 0
  93580. });
  93581. animationPP.setKeys(vignetteWeightKeys);
  93582. this._postProcessMove.animations.push(animationPP);
  93583. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93584. var vignetteStretchKeys = [];
  93585. vignetteStretchKeys.push({
  93586. frame: 0,
  93587. value: 0
  93588. });
  93589. vignetteStretchKeys.push({
  93590. frame: 5,
  93591. value: 10
  93592. });
  93593. vignetteStretchKeys.push({
  93594. frame: 11,
  93595. value: 0
  93596. });
  93597. animationPP2.setKeys(vignetteStretchKeys);
  93598. this._postProcessMove.animations.push(animationPP2);
  93599. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93600. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93601. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93602. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  93603. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93604. });
  93605. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  93606. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  93607. });
  93608. this._hideTeleportationTarget();
  93609. };
  93610. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  93611. if (normal) {
  93612. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  93613. if (angle < Math.PI / 2) {
  93614. normal.scaleInPlace(-1);
  93615. }
  93616. }
  93617. return normal;
  93618. };
  93619. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  93620. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93621. return;
  93622. }
  93623. var ray = gazer._getForwardRay(this._rayLength);
  93624. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93625. if (hit) {
  93626. // Populate the contrllers mesh that can be used for drag/drop
  93627. if (gazer._laserPointer) {
  93628. hit.originMesh = gazer._laserPointer.parent;
  93629. }
  93630. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  93631. }
  93632. gazer._currentHit = hit;
  93633. // Moving the gazeTracker on the mesh face targetted
  93634. if (hit && hit.pickedPoint) {
  93635. if (this._displayGaze) {
  93636. var multiplier = 1;
  93637. gazer._gazeTracker.isVisible = true;
  93638. if (gazer._isActionableMesh) {
  93639. multiplier = 3;
  93640. }
  93641. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  93642. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  93643. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  93644. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  93645. // To avoid z-fighting
  93646. var deltaFighting = 0.002;
  93647. if (pickNormal) {
  93648. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93649. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93650. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  93651. }
  93652. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  93653. if (gazer._gazeTracker.position.x < 0) {
  93654. gazer._gazeTracker.position.x += deltaFighting;
  93655. }
  93656. else {
  93657. gazer._gazeTracker.position.x -= deltaFighting;
  93658. }
  93659. if (gazer._gazeTracker.position.y < 0) {
  93660. gazer._gazeTracker.position.y += deltaFighting;
  93661. }
  93662. else {
  93663. gazer._gazeTracker.position.y -= deltaFighting;
  93664. }
  93665. if (gazer._gazeTracker.position.z < 0) {
  93666. gazer._gazeTracker.position.z += deltaFighting;
  93667. }
  93668. else {
  93669. gazer._gazeTracker.position.z -= deltaFighting;
  93670. }
  93671. }
  93672. // Changing the size of the laser pointer based on the distance from the targetted point
  93673. gazer._updatePointerDistance(hit.distance);
  93674. }
  93675. else {
  93676. gazer._updatePointerDistance();
  93677. gazer._gazeTracker.isVisible = false;
  93678. }
  93679. if (hit && hit.pickedMesh) {
  93680. // The object selected is the floor, we're in a teleportation scenario
  93681. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  93682. // Moving the teleportation area to this targetted point
  93683. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  93684. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  93685. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93686. }
  93687. gazer._currentMeshSelected = null;
  93688. if (gazer._teleportationRequestInitiated) {
  93689. this._moveTeleportationSelectorTo(hit, gazer, ray);
  93690. }
  93691. return;
  93692. }
  93693. // If not, we're in a selection scenario
  93694. //this._teleportationAllowed = false;
  93695. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  93696. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  93697. this.onNewMeshPicked.notifyObservers(hit);
  93698. gazer._currentMeshSelected = hit.pickedMesh;
  93699. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  93700. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  93701. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  93702. gazer._isActionableMesh = true;
  93703. }
  93704. else {
  93705. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93706. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93707. gazer._isActionableMesh = false;
  93708. }
  93709. try {
  93710. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  93711. }
  93712. catch (err) {
  93713. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  93714. }
  93715. }
  93716. else {
  93717. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93718. gazer._currentMeshSelected = null;
  93719. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93720. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93721. }
  93722. }
  93723. }
  93724. else {
  93725. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93726. gazer._currentMeshSelected = null;
  93727. //this._teleportationAllowed = false;
  93728. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93729. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93730. }
  93731. };
  93732. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  93733. if (mesh) {
  93734. this.onSelectedMeshUnselected.notifyObservers(mesh);
  93735. }
  93736. };
  93737. /**
  93738. * Sets the color of the laser ray from the vr controllers.
  93739. * @param color new color for the ray.
  93740. */
  93741. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  93742. if (this.leftController) {
  93743. this.leftController._setLaserPointerColor(color);
  93744. }
  93745. if (this.rightController) {
  93746. this.rightController._setLaserPointerColor(color);
  93747. }
  93748. };
  93749. /**
  93750. * Sets the color of the ray from the vr headsets gaze.
  93751. * @param color new color for the ray.
  93752. */
  93753. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  93754. if (!this._cameraGazer._gazeTracker.material) {
  93755. return;
  93756. }
  93757. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  93758. if (this.leftController) {
  93759. this.leftController._gazeTracker.material.emissiveColor = color;
  93760. }
  93761. if (this.rightController) {
  93762. this.rightController._gazeTracker.material.emissiveColor = color;
  93763. }
  93764. };
  93765. /**
  93766. * Exits VR and disposes of the vr experience helper
  93767. */
  93768. VRExperienceHelper.prototype.dispose = function () {
  93769. if (this.isInVRMode) {
  93770. this.exitVR();
  93771. }
  93772. if (this._postProcessMove) {
  93773. this._postProcessMove.dispose();
  93774. }
  93775. if (this._webVRCamera) {
  93776. this._webVRCamera.dispose();
  93777. }
  93778. if (this._vrDeviceOrientationCamera) {
  93779. this._vrDeviceOrientationCamera.dispose();
  93780. }
  93781. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  93782. document.body.removeChild(this._btnVR);
  93783. }
  93784. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  93785. this._deviceOrientationCamera.dispose();
  93786. }
  93787. if (this._cameraGazer) {
  93788. this._cameraGazer.dispose();
  93789. }
  93790. if (this.leftController) {
  93791. this.leftController.dispose();
  93792. }
  93793. if (this.rightController) {
  93794. this.rightController.dispose();
  93795. }
  93796. if (this._teleportationTarget) {
  93797. this._teleportationTarget.dispose();
  93798. }
  93799. this._floorMeshesCollection = [];
  93800. document.removeEventListener("keydown", this._onKeyDown);
  93801. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93802. window.removeEventListener("resize", this._onResize);
  93803. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  93804. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  93805. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  93806. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  93807. document.onmsfullscreenchange = null;
  93808. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  93809. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  93810. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  93811. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93812. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  93813. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  93814. this._scene.unregisterBeforeRender(this.beforeRender);
  93815. };
  93816. /**
  93817. * Gets the name of the VRExperienceHelper class
  93818. * @returns "VRExperienceHelper"
  93819. */
  93820. VRExperienceHelper.prototype.getClassName = function () {
  93821. return "VRExperienceHelper";
  93822. };
  93823. return VRExperienceHelper;
  93824. }());
  93825. BABYLON.VRExperienceHelper = VRExperienceHelper;
  93826. })(BABYLON || (BABYLON = {}));
  93827. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  93828. // Mainly based on these 2 articles :
  93829. // 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
  93830. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  93831. var BABYLON;
  93832. (function (BABYLON) {
  93833. /**
  93834. * Defines the potential axis of a Joystick
  93835. */
  93836. var JoystickAxis;
  93837. (function (JoystickAxis) {
  93838. /** X axis */
  93839. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  93840. /** Y axis */
  93841. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  93842. /** Z axis */
  93843. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  93844. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  93845. /**
  93846. * Class used to define virtual joystick (used in touch mode)
  93847. */
  93848. var VirtualJoystick = /** @class */ (function () {
  93849. /**
  93850. * Creates a new virtual joystick
  93851. * @param leftJoystick defines that the joystick is for left hand (false by default)
  93852. */
  93853. function VirtualJoystick(leftJoystick) {
  93854. var _this = this;
  93855. if (leftJoystick) {
  93856. this._leftJoystick = true;
  93857. }
  93858. else {
  93859. this._leftJoystick = false;
  93860. }
  93861. VirtualJoystick._globalJoystickIndex++;
  93862. // By default left & right arrow keys are moving the X
  93863. // and up & down keys are moving the Y
  93864. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93865. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93866. this.reverseLeftRight = false;
  93867. this.reverseUpDown = false;
  93868. // collections of pointers
  93869. this._touches = new BABYLON.StringDictionary();
  93870. this.deltaPosition = BABYLON.Vector3.Zero();
  93871. this._joystickSensibility = 25;
  93872. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  93873. this._onResize = function (evt) {
  93874. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93875. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93876. if (VirtualJoystick.vjCanvas) {
  93877. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  93878. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  93879. }
  93880. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  93881. };
  93882. // injecting a canvas element on top of the canvas 3D game
  93883. if (!VirtualJoystick.vjCanvas) {
  93884. window.addEventListener("resize", this._onResize, false);
  93885. VirtualJoystick.vjCanvas = document.createElement("canvas");
  93886. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93887. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93888. VirtualJoystick.vjCanvas.width = window.innerWidth;
  93889. VirtualJoystick.vjCanvas.height = window.innerHeight;
  93890. VirtualJoystick.vjCanvas.style.width = "100%";
  93891. VirtualJoystick.vjCanvas.style.height = "100%";
  93892. VirtualJoystick.vjCanvas.style.position = "absolute";
  93893. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  93894. VirtualJoystick.vjCanvas.style.top = "0px";
  93895. VirtualJoystick.vjCanvas.style.left = "0px";
  93896. VirtualJoystick.vjCanvas.style.zIndex = "5";
  93897. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  93898. // Support for jQuery PEP polyfill
  93899. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  93900. var context = VirtualJoystick.vjCanvas.getContext('2d');
  93901. if (!context) {
  93902. throw new Error("Unable to create canvas for virtual joystick");
  93903. }
  93904. VirtualJoystick.vjCanvasContext = context;
  93905. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  93906. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  93907. document.body.appendChild(VirtualJoystick.vjCanvas);
  93908. }
  93909. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  93910. this.pressed = false;
  93911. // default joystick color
  93912. this._joystickColor = "cyan";
  93913. this._joystickPointerID = -1;
  93914. // current joystick position
  93915. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  93916. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  93917. // origin joystick position
  93918. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  93919. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  93920. this._onPointerDownHandlerRef = function (evt) {
  93921. _this._onPointerDown(evt);
  93922. };
  93923. this._onPointerMoveHandlerRef = function (evt) {
  93924. _this._onPointerMove(evt);
  93925. };
  93926. this._onPointerUpHandlerRef = function (evt) {
  93927. _this._onPointerUp(evt);
  93928. };
  93929. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  93930. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  93931. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  93932. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  93933. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  93934. evt.preventDefault(); // Disables system menu
  93935. }, false);
  93936. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  93937. }
  93938. /**
  93939. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  93940. * @param newJoystickSensibility defines the new sensibility
  93941. */
  93942. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  93943. this._joystickSensibility = newJoystickSensibility;
  93944. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  93945. };
  93946. VirtualJoystick.prototype._onPointerDown = function (e) {
  93947. var positionOnScreenCondition;
  93948. e.preventDefault();
  93949. if (this._leftJoystick === true) {
  93950. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  93951. }
  93952. else {
  93953. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  93954. }
  93955. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  93956. // First contact will be dedicated to the virtual joystick
  93957. this._joystickPointerID = e.pointerId;
  93958. this._joystickPointerStartPos.x = e.clientX;
  93959. this._joystickPointerStartPos.y = e.clientY;
  93960. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  93961. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  93962. this._deltaJoystickVector.x = 0;
  93963. this._deltaJoystickVector.y = 0;
  93964. this.pressed = true;
  93965. this._touches.add(e.pointerId.toString(), e);
  93966. }
  93967. else {
  93968. // You can only trigger the action buttons with a joystick declared
  93969. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  93970. this._action();
  93971. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  93972. }
  93973. }
  93974. };
  93975. VirtualJoystick.prototype._onPointerMove = function (e) {
  93976. // If the current pointer is the one associated to the joystick (first touch contact)
  93977. if (this._joystickPointerID == e.pointerId) {
  93978. this._joystickPointerPos.x = e.clientX;
  93979. this._joystickPointerPos.y = e.clientY;
  93980. this._deltaJoystickVector = this._joystickPointerPos.clone();
  93981. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  93982. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  93983. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  93984. switch (this._axisTargetedByLeftAndRight) {
  93985. case JoystickAxis.X:
  93986. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  93987. break;
  93988. case JoystickAxis.Y:
  93989. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  93990. break;
  93991. case JoystickAxis.Z:
  93992. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  93993. break;
  93994. }
  93995. var directionUpDown = this.reverseUpDown ? 1 : -1;
  93996. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  93997. switch (this._axisTargetedByUpAndDown) {
  93998. case JoystickAxis.X:
  93999. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  94000. break;
  94001. case JoystickAxis.Y:
  94002. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  94003. break;
  94004. case JoystickAxis.Z:
  94005. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  94006. break;
  94007. }
  94008. }
  94009. else {
  94010. var data = this._touches.get(e.pointerId.toString());
  94011. if (data) {
  94012. data.x = e.clientX;
  94013. data.y = e.clientY;
  94014. }
  94015. }
  94016. };
  94017. VirtualJoystick.prototype._onPointerUp = function (e) {
  94018. if (this._joystickPointerID == e.pointerId) {
  94019. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  94020. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  94021. this._joystickPointerID = -1;
  94022. this.pressed = false;
  94023. }
  94024. else {
  94025. var touch = this._touches.get(e.pointerId.toString());
  94026. if (touch) {
  94027. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94028. }
  94029. }
  94030. this._deltaJoystickVector.x = 0;
  94031. this._deltaJoystickVector.y = 0;
  94032. this._touches.remove(e.pointerId.toString());
  94033. };
  94034. /**
  94035. * Change the color of the virtual joystick
  94036. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  94037. */
  94038. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  94039. this._joystickColor = newColor;
  94040. };
  94041. /**
  94042. * Defines a callback to call when the joystick is touched
  94043. * @param action defines the callback
  94044. */
  94045. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  94046. this._action = action;
  94047. };
  94048. /**
  94049. * Defines which axis you'd like to control for left & right
  94050. * @param axis defines the axis to use
  94051. */
  94052. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  94053. switch (axis) {
  94054. case JoystickAxis.X:
  94055. case JoystickAxis.Y:
  94056. case JoystickAxis.Z:
  94057. this._axisTargetedByLeftAndRight = axis;
  94058. break;
  94059. default:
  94060. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94061. break;
  94062. }
  94063. };
  94064. /**
  94065. * Defines which axis you'd like to control for up & down
  94066. * @param axis defines the axis to use
  94067. */
  94068. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  94069. switch (axis) {
  94070. case JoystickAxis.X:
  94071. case JoystickAxis.Y:
  94072. case JoystickAxis.Z:
  94073. this._axisTargetedByUpAndDown = axis;
  94074. break;
  94075. default:
  94076. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  94077. break;
  94078. }
  94079. };
  94080. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  94081. var _this = this;
  94082. if (this.pressed) {
  94083. this._touches.forEach(function (key, touch) {
  94084. if (touch.pointerId === _this._joystickPointerID) {
  94085. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  94086. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  94087. VirtualJoystick.vjCanvasContext.beginPath();
  94088. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  94089. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94090. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  94091. VirtualJoystick.vjCanvasContext.stroke();
  94092. VirtualJoystick.vjCanvasContext.closePath();
  94093. VirtualJoystick.vjCanvasContext.beginPath();
  94094. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94095. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  94096. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  94097. VirtualJoystick.vjCanvasContext.stroke();
  94098. VirtualJoystick.vjCanvasContext.closePath();
  94099. VirtualJoystick.vjCanvasContext.beginPath();
  94100. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94101. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  94102. VirtualJoystick.vjCanvasContext.stroke();
  94103. VirtualJoystick.vjCanvasContext.closePath();
  94104. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  94105. }
  94106. else {
  94107. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94108. VirtualJoystick.vjCanvasContext.beginPath();
  94109. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  94110. VirtualJoystick.vjCanvasContext.beginPath();
  94111. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  94112. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  94113. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  94114. VirtualJoystick.vjCanvasContext.stroke();
  94115. VirtualJoystick.vjCanvasContext.closePath();
  94116. touch.prevX = touch.x;
  94117. touch.prevY = touch.y;
  94118. }
  94119. ;
  94120. });
  94121. }
  94122. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94123. };
  94124. /**
  94125. * Release internal HTML canvas
  94126. */
  94127. VirtualJoystick.prototype.releaseCanvas = function () {
  94128. if (VirtualJoystick.vjCanvas) {
  94129. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  94130. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  94131. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  94132. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  94133. window.removeEventListener("resize", this._onResize);
  94134. document.body.removeChild(VirtualJoystick.vjCanvas);
  94135. VirtualJoystick.vjCanvas = null;
  94136. }
  94137. };
  94138. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  94139. VirtualJoystick._globalJoystickIndex = 0;
  94140. return VirtualJoystick;
  94141. }());
  94142. BABYLON.VirtualJoystick = VirtualJoystick;
  94143. })(BABYLON || (BABYLON = {}));
  94144. //# sourceMappingURL=babylon.virtualJoystick.js.map
  94145. var BABYLON;
  94146. (function (BABYLON) {
  94147. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  94148. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  94149. });
  94150. // We're mainly based on the logic defined into the FreeCamera code
  94151. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  94152. __extends(VirtualJoysticksCamera, _super);
  94153. function VirtualJoysticksCamera(name, position, scene) {
  94154. var _this = _super.call(this, name, position, scene) || this;
  94155. _this.inputs.addVirtualJoystick();
  94156. return _this;
  94157. }
  94158. VirtualJoysticksCamera.prototype.getClassName = function () {
  94159. return "VirtualJoysticksCamera";
  94160. };
  94161. return VirtualJoysticksCamera;
  94162. }(BABYLON.FreeCamera));
  94163. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  94164. })(BABYLON || (BABYLON = {}));
  94165. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  94166. var BABYLON;
  94167. (function (BABYLON) {
  94168. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  94169. function FreeCameraVirtualJoystickInput() {
  94170. }
  94171. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  94172. return this._leftjoystick;
  94173. };
  94174. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  94175. return this._rightjoystick;
  94176. };
  94177. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  94178. if (this._leftjoystick) {
  94179. var camera = this.camera;
  94180. var speed = camera._computeLocalCameraSpeed() * 50;
  94181. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  94182. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  94183. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  94184. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  94185. if (!this._leftjoystick.pressed) {
  94186. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  94187. }
  94188. if (!this._rightjoystick.pressed) {
  94189. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  94190. }
  94191. }
  94192. };
  94193. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  94194. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  94195. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  94196. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  94197. this._leftjoystick.setJoystickSensibility(0.15);
  94198. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  94199. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  94200. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  94201. this._rightjoystick.reverseUpDown = true;
  94202. this._rightjoystick.setJoystickSensibility(0.05);
  94203. this._rightjoystick.setJoystickColor("yellow");
  94204. };
  94205. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  94206. this._leftjoystick.releaseCanvas();
  94207. this._rightjoystick.releaseCanvas();
  94208. };
  94209. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  94210. return "FreeCameraVirtualJoystickInput";
  94211. };
  94212. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  94213. return "virtualJoystick";
  94214. };
  94215. return FreeCameraVirtualJoystickInput;
  94216. }());
  94217. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  94218. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  94219. })(BABYLON || (BABYLON = {}));
  94220. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  94221. var BABYLON;
  94222. (function (BABYLON) {
  94223. var SimplificationSettings = /** @class */ (function () {
  94224. function SimplificationSettings(quality, distance, optimizeMesh) {
  94225. this.quality = quality;
  94226. this.distance = distance;
  94227. this.optimizeMesh = optimizeMesh;
  94228. }
  94229. return SimplificationSettings;
  94230. }());
  94231. BABYLON.SimplificationSettings = SimplificationSettings;
  94232. var SimplificationQueue = /** @class */ (function () {
  94233. function SimplificationQueue() {
  94234. this.running = false;
  94235. this._simplificationArray = [];
  94236. }
  94237. SimplificationQueue.prototype.addTask = function (task) {
  94238. this._simplificationArray.push(task);
  94239. };
  94240. SimplificationQueue.prototype.executeNext = function () {
  94241. var task = this._simplificationArray.pop();
  94242. if (task) {
  94243. this.running = true;
  94244. this.runSimplification(task);
  94245. }
  94246. else {
  94247. this.running = false;
  94248. }
  94249. };
  94250. SimplificationQueue.prototype.runSimplification = function (task) {
  94251. var _this = this;
  94252. if (task.parallelProcessing) {
  94253. //parallel simplifier
  94254. task.settings.forEach(function (setting) {
  94255. var simplifier = _this.getSimplifier(task);
  94256. simplifier.simplify(setting, function (newMesh) {
  94257. task.mesh.addLODLevel(setting.distance, newMesh);
  94258. newMesh.isVisible = true;
  94259. //check if it is the last
  94260. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  94261. //all done, run the success callback.
  94262. task.successCallback();
  94263. }
  94264. _this.executeNext();
  94265. });
  94266. });
  94267. }
  94268. else {
  94269. //single simplifier.
  94270. var simplifier = this.getSimplifier(task);
  94271. var runDecimation = function (setting, callback) {
  94272. simplifier.simplify(setting, function (newMesh) {
  94273. task.mesh.addLODLevel(setting.distance, newMesh);
  94274. newMesh.isVisible = true;
  94275. //run the next quality level
  94276. callback();
  94277. });
  94278. };
  94279. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  94280. runDecimation(task.settings[loop.index], function () {
  94281. loop.executeNext();
  94282. });
  94283. }, function () {
  94284. //execution ended, run the success callback.
  94285. if (task.successCallback) {
  94286. task.successCallback();
  94287. }
  94288. _this.executeNext();
  94289. });
  94290. }
  94291. };
  94292. SimplificationQueue.prototype.getSimplifier = function (task) {
  94293. switch (task.simplificationType) {
  94294. case SimplificationType.QUADRATIC:
  94295. default:
  94296. return new QuadraticErrorSimplification(task.mesh);
  94297. }
  94298. };
  94299. return SimplificationQueue;
  94300. }());
  94301. BABYLON.SimplificationQueue = SimplificationQueue;
  94302. /**
  94303. * The implemented types of simplification
  94304. * At the moment only Quadratic Error Decimation is implemented
  94305. */
  94306. var SimplificationType;
  94307. (function (SimplificationType) {
  94308. /** Quadratic error decimation */
  94309. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  94310. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  94311. var DecimationTriangle = /** @class */ (function () {
  94312. function DecimationTriangle(vertices) {
  94313. this.vertices = vertices;
  94314. this.error = new Array(4);
  94315. this.deleted = false;
  94316. this.isDirty = false;
  94317. this.deletePending = false;
  94318. this.borderFactor = 0;
  94319. }
  94320. return DecimationTriangle;
  94321. }());
  94322. BABYLON.DecimationTriangle = DecimationTriangle;
  94323. var DecimationVertex = /** @class */ (function () {
  94324. function DecimationVertex(position, id) {
  94325. this.position = position;
  94326. this.id = id;
  94327. this.isBorder = true;
  94328. this.q = new QuadraticMatrix();
  94329. this.triangleCount = 0;
  94330. this.triangleStart = 0;
  94331. this.originalOffsets = [];
  94332. }
  94333. DecimationVertex.prototype.updatePosition = function (newPosition) {
  94334. this.position.copyFrom(newPosition);
  94335. };
  94336. return DecimationVertex;
  94337. }());
  94338. BABYLON.DecimationVertex = DecimationVertex;
  94339. var QuadraticMatrix = /** @class */ (function () {
  94340. function QuadraticMatrix(data) {
  94341. this.data = new Array(10);
  94342. for (var i = 0; i < 10; ++i) {
  94343. if (data && data[i]) {
  94344. this.data[i] = data[i];
  94345. }
  94346. else {
  94347. this.data[i] = 0;
  94348. }
  94349. }
  94350. }
  94351. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  94352. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  94353. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  94354. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  94355. return det;
  94356. };
  94357. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  94358. for (var i = 0; i < 10; ++i) {
  94359. this.data[i] += matrix.data[i];
  94360. }
  94361. };
  94362. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  94363. for (var i = 0; i < 10; ++i) {
  94364. this.data[i] += data[i];
  94365. }
  94366. };
  94367. QuadraticMatrix.prototype.add = function (matrix) {
  94368. var m = new QuadraticMatrix();
  94369. for (var i = 0; i < 10; ++i) {
  94370. m.data[i] = this.data[i] + matrix.data[i];
  94371. }
  94372. return m;
  94373. };
  94374. QuadraticMatrix.FromData = function (a, b, c, d) {
  94375. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  94376. };
  94377. //returning an array to avoid garbage collection
  94378. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  94379. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  94380. };
  94381. return QuadraticMatrix;
  94382. }());
  94383. BABYLON.QuadraticMatrix = QuadraticMatrix;
  94384. var Reference = /** @class */ (function () {
  94385. function Reference(vertexId, triangleId) {
  94386. this.vertexId = vertexId;
  94387. this.triangleId = triangleId;
  94388. }
  94389. return Reference;
  94390. }());
  94391. BABYLON.Reference = Reference;
  94392. /**
  94393. * An implementation of the Quadratic Error simplification algorithm.
  94394. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  94395. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  94396. * @author RaananW
  94397. */
  94398. var QuadraticErrorSimplification = /** @class */ (function () {
  94399. function QuadraticErrorSimplification(_mesh) {
  94400. this._mesh = _mesh;
  94401. this.syncIterations = 5000;
  94402. this.aggressiveness = 7;
  94403. this.decimationIterations = 100;
  94404. this.boundingBoxEpsilon = BABYLON.Epsilon;
  94405. }
  94406. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  94407. var _this = this;
  94408. this.initDecimatedMesh();
  94409. //iterating through the submeshes array, one after the other.
  94410. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  94411. _this.initWithMesh(loop.index, function () {
  94412. _this.runDecimation(settings, loop.index, function () {
  94413. loop.executeNext();
  94414. });
  94415. }, settings.optimizeMesh);
  94416. }, function () {
  94417. setTimeout(function () {
  94418. successCallback(_this._reconstructedMesh);
  94419. }, 0);
  94420. });
  94421. };
  94422. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  94423. var _this = this;
  94424. var targetCount = ~~(this.triangles.length * settings.quality);
  94425. var deletedTriangles = 0;
  94426. var triangleCount = this.triangles.length;
  94427. var iterationFunction = function (iteration, callback) {
  94428. setTimeout(function () {
  94429. if (iteration % 5 === 0) {
  94430. _this.updateMesh(iteration === 0);
  94431. }
  94432. for (var i = 0; i < _this.triangles.length; ++i) {
  94433. _this.triangles[i].isDirty = false;
  94434. }
  94435. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  94436. var trianglesIterator = function (i) {
  94437. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  94438. var t = _this.triangles[tIdx];
  94439. if (!t)
  94440. return;
  94441. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  94442. return;
  94443. }
  94444. for (var j = 0; j < 3; ++j) {
  94445. if (t.error[j] < threshold) {
  94446. var deleted0 = [];
  94447. var deleted1 = [];
  94448. var v0 = t.vertices[j];
  94449. var v1 = t.vertices[(j + 1) % 3];
  94450. if (v0.isBorder || v1.isBorder)
  94451. continue;
  94452. var p = BABYLON.Vector3.Zero();
  94453. var n = BABYLON.Vector3.Zero();
  94454. var uv = BABYLON.Vector2.Zero();
  94455. var color = new BABYLON.Color4(0, 0, 0, 1);
  94456. _this.calculateError(v0, v1, p, n, uv, color);
  94457. var delTr = new Array();
  94458. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  94459. continue;
  94460. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  94461. continue;
  94462. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  94463. continue;
  94464. var uniqueArray = new Array();
  94465. delTr.forEach(function (deletedT) {
  94466. if (uniqueArray.indexOf(deletedT) === -1) {
  94467. deletedT.deletePending = true;
  94468. uniqueArray.push(deletedT);
  94469. }
  94470. });
  94471. if (uniqueArray.length % 2 !== 0) {
  94472. continue;
  94473. }
  94474. v0.q = v1.q.add(v0.q);
  94475. v0.updatePosition(p);
  94476. var tStart = _this.references.length;
  94477. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  94478. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  94479. var tCount = _this.references.length - tStart;
  94480. if (tCount <= v0.triangleCount) {
  94481. if (tCount) {
  94482. for (var c = 0; c < tCount; c++) {
  94483. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  94484. }
  94485. }
  94486. }
  94487. else {
  94488. v0.triangleStart = tStart;
  94489. }
  94490. v0.triangleCount = tCount;
  94491. break;
  94492. }
  94493. }
  94494. };
  94495. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  94496. }, 0);
  94497. };
  94498. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  94499. if (triangleCount - deletedTriangles <= targetCount)
  94500. loop.breakLoop();
  94501. else {
  94502. iterationFunction(loop.index, function () {
  94503. loop.executeNext();
  94504. });
  94505. }
  94506. }, function () {
  94507. setTimeout(function () {
  94508. //reconstruct this part of the mesh
  94509. _this.reconstructMesh(submeshIndex);
  94510. successCallback();
  94511. }, 0);
  94512. });
  94513. };
  94514. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  94515. var _this = this;
  94516. this.vertices = [];
  94517. this.triangles = [];
  94518. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  94519. var indices = this._mesh.getIndices();
  94520. var submesh = this._mesh.subMeshes[submeshIndex];
  94521. var findInVertices = function (positionToSearch) {
  94522. if (optimizeMesh) {
  94523. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  94524. if (_this.vertices[ii].position.equals(positionToSearch)) {
  94525. return _this.vertices[ii];
  94526. }
  94527. }
  94528. }
  94529. return null;
  94530. };
  94531. var vertexReferences = [];
  94532. var vertexInit = function (i) {
  94533. if (!positionData) {
  94534. return;
  94535. }
  94536. var offset = i + submesh.verticesStart;
  94537. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  94538. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  94539. vertex.originalOffsets.push(offset);
  94540. if (vertex.id === _this.vertices.length) {
  94541. _this.vertices.push(vertex);
  94542. }
  94543. vertexReferences.push(vertex.id);
  94544. };
  94545. //var totalVertices = mesh.getTotalVertices();
  94546. var totalVertices = submesh.verticesCount;
  94547. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  94548. var indicesInit = function (i) {
  94549. if (!indices) {
  94550. return;
  94551. }
  94552. var offset = (submesh.indexStart / 3) + i;
  94553. var pos = (offset * 3);
  94554. var i0 = indices[pos + 0];
  94555. var i1 = indices[pos + 1];
  94556. var i2 = indices[pos + 2];
  94557. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  94558. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  94559. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  94560. var triangle = new DecimationTriangle([v0, v1, v2]);
  94561. triangle.originalOffset = pos;
  94562. _this.triangles.push(triangle);
  94563. };
  94564. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  94565. _this.init(callback);
  94566. });
  94567. });
  94568. };
  94569. QuadraticErrorSimplification.prototype.init = function (callback) {
  94570. var _this = this;
  94571. var triangleInit1 = function (i) {
  94572. var t = _this.triangles[i];
  94573. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  94574. for (var j = 0; j < 3; j++) {
  94575. 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))));
  94576. }
  94577. };
  94578. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  94579. var triangleInit2 = function (i) {
  94580. var t = _this.triangles[i];
  94581. for (var j = 0; j < 3; ++j) {
  94582. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  94583. }
  94584. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94585. };
  94586. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  94587. callback();
  94588. });
  94589. });
  94590. };
  94591. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  94592. var newTriangles = [];
  94593. var i;
  94594. for (i = 0; i < this.vertices.length; ++i) {
  94595. this.vertices[i].triangleCount = 0;
  94596. }
  94597. var t;
  94598. var j;
  94599. for (i = 0; i < this.triangles.length; ++i) {
  94600. if (!this.triangles[i].deleted) {
  94601. t = this.triangles[i];
  94602. for (j = 0; j < 3; ++j) {
  94603. t.vertices[j].triangleCount = 1;
  94604. }
  94605. newTriangles.push(t);
  94606. }
  94607. }
  94608. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  94609. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  94610. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  94611. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  94612. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  94613. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  94614. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  94615. var vertexCount = 0;
  94616. for (i = 0; i < this.vertices.length; ++i) {
  94617. var vertex = this.vertices[i];
  94618. vertex.id = vertexCount;
  94619. if (vertex.triangleCount) {
  94620. vertex.originalOffsets.forEach(function (originalOffset) {
  94621. if (!normalData) {
  94622. return;
  94623. }
  94624. newPositionData.push(vertex.position.x);
  94625. newPositionData.push(vertex.position.y);
  94626. newPositionData.push(vertex.position.z);
  94627. newNormalData.push(normalData[originalOffset * 3]);
  94628. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  94629. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  94630. if (uvs && uvs.length) {
  94631. newUVsData.push(uvs[(originalOffset * 2)]);
  94632. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  94633. }
  94634. else if (colorsData && colorsData.length) {
  94635. newColorsData.push(colorsData[(originalOffset * 4)]);
  94636. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  94637. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  94638. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  94639. }
  94640. ++vertexCount;
  94641. });
  94642. }
  94643. }
  94644. var startingIndex = this._reconstructedMesh.getTotalIndices();
  94645. var startingVertex = this._reconstructedMesh.getTotalVertices();
  94646. var submeshesArray = this._reconstructedMesh.subMeshes;
  94647. this._reconstructedMesh.subMeshes = [];
  94648. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  94649. var originalIndices = this._mesh.getIndices();
  94650. for (i = 0; i < newTriangles.length; ++i) {
  94651. t = newTriangles[i]; //now get the new referencing point for each vertex
  94652. [0, 1, 2].forEach(function (idx) {
  94653. var id = originalIndices[t.originalOffset + idx];
  94654. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  94655. if (offset < 0)
  94656. offset = 0;
  94657. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  94658. });
  94659. }
  94660. //overwriting the old vertex buffers and indices.
  94661. this._reconstructedMesh.setIndices(newIndicesArray);
  94662. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  94663. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  94664. if (newUVsData.length > 0)
  94665. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  94666. if (newColorsData.length > 0)
  94667. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  94668. //create submesh
  94669. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  94670. if (submeshIndex > 0) {
  94671. this._reconstructedMesh.subMeshes = [];
  94672. submeshesArray.forEach(function (submesh) {
  94673. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  94674. });
  94675. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  94676. }
  94677. };
  94678. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  94679. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  94680. this._reconstructedMesh.material = this._mesh.material;
  94681. this._reconstructedMesh.parent = this._mesh.parent;
  94682. this._reconstructedMesh.isVisible = false;
  94683. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  94684. };
  94685. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  94686. for (var i = 0; i < vertex1.triangleCount; ++i) {
  94687. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  94688. if (t.deleted)
  94689. continue;
  94690. var s = this.references[vertex1.triangleStart + i].vertexId;
  94691. var v1 = t.vertices[(s + 1) % 3];
  94692. var v2 = t.vertices[(s + 2) % 3];
  94693. if ((v1 === vertex2 || v2 === vertex2)) {
  94694. deletedArray[i] = true;
  94695. delTr.push(t);
  94696. continue;
  94697. }
  94698. var d1 = v1.position.subtract(point);
  94699. d1 = d1.normalize();
  94700. var d2 = v2.position.subtract(point);
  94701. d2 = d2.normalize();
  94702. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  94703. return true;
  94704. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  94705. deletedArray[i] = false;
  94706. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  94707. return true;
  94708. }
  94709. return false;
  94710. };
  94711. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  94712. var newDeleted = deletedTriangles;
  94713. for (var i = 0; i < vertex.triangleCount; ++i) {
  94714. var ref = this.references[vertex.triangleStart + i];
  94715. var t = this.triangles[ref.triangleId];
  94716. if (t.deleted)
  94717. continue;
  94718. if (deletedArray[i] && t.deletePending) {
  94719. t.deleted = true;
  94720. newDeleted++;
  94721. continue;
  94722. }
  94723. t.vertices[ref.vertexId] = origVertex;
  94724. t.isDirty = true;
  94725. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  94726. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  94727. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  94728. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94729. this.references.push(ref);
  94730. }
  94731. return newDeleted;
  94732. };
  94733. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  94734. for (var i = 0; i < this.vertices.length; ++i) {
  94735. var vCount = [];
  94736. var vId = [];
  94737. var v = this.vertices[i];
  94738. var j;
  94739. for (j = 0; j < v.triangleCount; ++j) {
  94740. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  94741. for (var ii = 0; ii < 3; ii++) {
  94742. var ofs = 0;
  94743. var vv = triangle.vertices[ii];
  94744. while (ofs < vCount.length) {
  94745. if (vId[ofs] === vv.id)
  94746. break;
  94747. ++ofs;
  94748. }
  94749. if (ofs === vCount.length) {
  94750. vCount.push(1);
  94751. vId.push(vv.id);
  94752. }
  94753. else {
  94754. vCount[ofs]++;
  94755. }
  94756. }
  94757. }
  94758. for (j = 0; j < vCount.length; ++j) {
  94759. if (vCount[j] === 1) {
  94760. this.vertices[vId[j]].isBorder = true;
  94761. }
  94762. else {
  94763. this.vertices[vId[j]].isBorder = false;
  94764. }
  94765. }
  94766. }
  94767. };
  94768. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  94769. if (identifyBorders === void 0) { identifyBorders = false; }
  94770. var i;
  94771. if (!identifyBorders) {
  94772. var newTrianglesVector = [];
  94773. for (i = 0; i < this.triangles.length; ++i) {
  94774. if (!this.triangles[i].deleted) {
  94775. newTrianglesVector.push(this.triangles[i]);
  94776. }
  94777. }
  94778. this.triangles = newTrianglesVector;
  94779. }
  94780. for (i = 0; i < this.vertices.length; ++i) {
  94781. this.vertices[i].triangleCount = 0;
  94782. this.vertices[i].triangleStart = 0;
  94783. }
  94784. var t;
  94785. var j;
  94786. var v;
  94787. for (i = 0; i < this.triangles.length; ++i) {
  94788. t = this.triangles[i];
  94789. for (j = 0; j < 3; ++j) {
  94790. v = t.vertices[j];
  94791. v.triangleCount++;
  94792. }
  94793. }
  94794. var tStart = 0;
  94795. for (i = 0; i < this.vertices.length; ++i) {
  94796. this.vertices[i].triangleStart = tStart;
  94797. tStart += this.vertices[i].triangleCount;
  94798. this.vertices[i].triangleCount = 0;
  94799. }
  94800. var newReferences = new Array(this.triangles.length * 3);
  94801. for (i = 0; i < this.triangles.length; ++i) {
  94802. t = this.triangles[i];
  94803. for (j = 0; j < 3; ++j) {
  94804. v = t.vertices[j];
  94805. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  94806. v.triangleCount++;
  94807. }
  94808. }
  94809. this.references = newReferences;
  94810. if (identifyBorders) {
  94811. this.identifyBorder();
  94812. }
  94813. };
  94814. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  94815. var x = point.x;
  94816. var y = point.y;
  94817. var z = point.z;
  94818. 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
  94819. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  94820. };
  94821. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  94822. var q = vertex1.q.add(vertex2.q);
  94823. var border = vertex1.isBorder && vertex2.isBorder;
  94824. var error = 0;
  94825. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  94826. if (qDet !== 0 && !border) {
  94827. if (!pointResult) {
  94828. pointResult = BABYLON.Vector3.Zero();
  94829. }
  94830. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  94831. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  94832. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  94833. error = this.vertexError(q, pointResult);
  94834. }
  94835. else {
  94836. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  94837. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  94838. var error1 = this.vertexError(q, vertex1.position);
  94839. var error2 = this.vertexError(q, vertex2.position);
  94840. var error3 = this.vertexError(q, p3);
  94841. error = Math.min(error1, error2, error3);
  94842. if (error === error1) {
  94843. if (pointResult) {
  94844. pointResult.copyFrom(vertex1.position);
  94845. }
  94846. }
  94847. else if (error === error2) {
  94848. if (pointResult) {
  94849. pointResult.copyFrom(vertex2.position);
  94850. }
  94851. }
  94852. else {
  94853. if (pointResult) {
  94854. pointResult.copyFrom(p3);
  94855. }
  94856. }
  94857. }
  94858. return error;
  94859. };
  94860. return QuadraticErrorSimplification;
  94861. }());
  94862. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  94863. })(BABYLON || (BABYLON = {}));
  94864. //# sourceMappingURL=babylon.meshSimplification.js.map
  94865. var BABYLON;
  94866. (function (BABYLON) {
  94867. var MeshLODLevel = /** @class */ (function () {
  94868. function MeshLODLevel(distance, mesh) {
  94869. this.distance = distance;
  94870. this.mesh = mesh;
  94871. }
  94872. return MeshLODLevel;
  94873. }());
  94874. BABYLON.MeshLODLevel = MeshLODLevel;
  94875. })(BABYLON || (BABYLON = {}));
  94876. //# sourceMappingURL=babylon.meshLODLevel.js.map
  94877. var BABYLON;
  94878. (function (BABYLON) {
  94879. /**
  94880. * Defines the root class used to create scene optimization to use with SceneOptimizer
  94881. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94882. */
  94883. var SceneOptimization = /** @class */ (function () {
  94884. /**
  94885. * Creates the SceneOptimization object
  94886. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94887. * @param desc defines the description associated with the optimization
  94888. */
  94889. function SceneOptimization(
  94890. /**
  94891. * Defines the priority of this optimization (0 by default which means first in the list)
  94892. */
  94893. priority) {
  94894. if (priority === void 0) { priority = 0; }
  94895. this.priority = priority;
  94896. }
  94897. /**
  94898. * Gets a string describing the action executed by the current optimization
  94899. * @returns description string
  94900. */
  94901. SceneOptimization.prototype.getDescription = function () {
  94902. return "";
  94903. };
  94904. /**
  94905. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94906. * @param scene defines the current scene where to apply this optimization
  94907. * @param optimizer defines the current optimizer
  94908. * @returns true if everything that can be done was applied
  94909. */
  94910. SceneOptimization.prototype.apply = function (scene, optimizer) {
  94911. return true;
  94912. };
  94913. ;
  94914. return SceneOptimization;
  94915. }());
  94916. BABYLON.SceneOptimization = SceneOptimization;
  94917. /**
  94918. * Defines an optimization used to reduce the size of render target textures
  94919. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94920. */
  94921. var TextureOptimization = /** @class */ (function (_super) {
  94922. __extends(TextureOptimization, _super);
  94923. /**
  94924. * Creates the TextureOptimization object
  94925. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94926. * @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
  94927. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  94928. */
  94929. function TextureOptimization(
  94930. /**
  94931. * Defines the priority of this optimization (0 by default which means first in the list)
  94932. */
  94933. priority,
  94934. /**
  94935. * 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
  94936. */
  94937. maximumSize,
  94938. /**
  94939. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  94940. */
  94941. step) {
  94942. if (priority === void 0) { priority = 0; }
  94943. if (maximumSize === void 0) { maximumSize = 1024; }
  94944. if (step === void 0) { step = 0.5; }
  94945. var _this = _super.call(this, priority) || this;
  94946. _this.priority = priority;
  94947. _this.maximumSize = maximumSize;
  94948. _this.step = step;
  94949. return _this;
  94950. }
  94951. /**
  94952. * Gets a string describing the action executed by the current optimization
  94953. * @returns description string
  94954. */
  94955. TextureOptimization.prototype.getDescription = function () {
  94956. return "Reducing render target texture size to " + this.maximumSize;
  94957. };
  94958. /**
  94959. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94960. * @param scene defines the current scene where to apply this optimization
  94961. * @param optimizer defines the current optimizer
  94962. * @returns true if everything that can be done was applied
  94963. */
  94964. TextureOptimization.prototype.apply = function (scene, optimizer) {
  94965. var allDone = true;
  94966. for (var index = 0; index < scene.textures.length; index++) {
  94967. var texture = scene.textures[index];
  94968. if (!texture.canRescale || texture.getContext) {
  94969. continue;
  94970. }
  94971. var currentSize = texture.getSize();
  94972. var maxDimension = Math.max(currentSize.width, currentSize.height);
  94973. if (maxDimension > this.maximumSize) {
  94974. texture.scale(this.step);
  94975. allDone = false;
  94976. }
  94977. }
  94978. return allDone;
  94979. };
  94980. return TextureOptimization;
  94981. }(SceneOptimization));
  94982. BABYLON.TextureOptimization = TextureOptimization;
  94983. /**
  94984. * Defines an optimization used to increase or decrease the rendering resolution
  94985. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94986. */
  94987. var HardwareScalingOptimization = /** @class */ (function (_super) {
  94988. __extends(HardwareScalingOptimization, _super);
  94989. /**
  94990. * Creates the HardwareScalingOptimization object
  94991. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94992. * @param maximumScale defines the maximum scale to use (2 by default)
  94993. * @param step defines the step to use between two passes (0.5 by default)
  94994. */
  94995. function HardwareScalingOptimization(
  94996. /**
  94997. * Defines the priority of this optimization (0 by default which means first in the list)
  94998. */
  94999. priority,
  95000. /**
  95001. * Defines the maximum scale to use (2 by default)
  95002. */
  95003. maximumScale,
  95004. /**
  95005. * Defines the step to use between two passes (0.5 by default)
  95006. */
  95007. step) {
  95008. if (priority === void 0) { priority = 0; }
  95009. if (maximumScale === void 0) { maximumScale = 2; }
  95010. if (step === void 0) { step = 0.25; }
  95011. var _this = _super.call(this, priority) || this;
  95012. _this.priority = priority;
  95013. _this.maximumScale = maximumScale;
  95014. _this.step = step;
  95015. _this._currentScale = -1;
  95016. _this._directionOffset = 1;
  95017. return _this;
  95018. }
  95019. /**
  95020. * Gets a string describing the action executed by the current optimization
  95021. * @return description string
  95022. */
  95023. HardwareScalingOptimization.prototype.getDescription = function () {
  95024. return "Setting hardware scaling level to " + this._currentScale;
  95025. };
  95026. /**
  95027. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95028. * @param scene defines the current scene where to apply this optimization
  95029. * @param optimizer defines the current optimizer
  95030. * @returns true if everything that can be done was applied
  95031. */
  95032. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  95033. if (this._currentScale === -1) {
  95034. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  95035. if (this._currentScale > this.maximumScale) {
  95036. this._directionOffset = -1;
  95037. }
  95038. }
  95039. this._currentScale += this._directionOffset * this.step;
  95040. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  95041. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  95042. };
  95043. ;
  95044. return HardwareScalingOptimization;
  95045. }(SceneOptimization));
  95046. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  95047. /**
  95048. * Defines an optimization used to remove shadows
  95049. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95050. */
  95051. var ShadowsOptimization = /** @class */ (function (_super) {
  95052. __extends(ShadowsOptimization, _super);
  95053. function ShadowsOptimization() {
  95054. return _super !== null && _super.apply(this, arguments) || this;
  95055. }
  95056. /**
  95057. * Gets a string describing the action executed by the current optimization
  95058. * @return description string
  95059. */
  95060. ShadowsOptimization.prototype.getDescription = function () {
  95061. return "Turning shadows on/off";
  95062. };
  95063. /**
  95064. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95065. * @param scene defines the current scene where to apply this optimization
  95066. * @param optimizer defines the current optimizer
  95067. * @returns true if everything that can be done was applied
  95068. */
  95069. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  95070. scene.shadowsEnabled = optimizer.isInImprovementMode;
  95071. return true;
  95072. };
  95073. ;
  95074. return ShadowsOptimization;
  95075. }(SceneOptimization));
  95076. BABYLON.ShadowsOptimization = ShadowsOptimization;
  95077. /**
  95078. * Defines an optimization used to turn post-processes off
  95079. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95080. */
  95081. var PostProcessesOptimization = /** @class */ (function (_super) {
  95082. __extends(PostProcessesOptimization, _super);
  95083. function PostProcessesOptimization() {
  95084. return _super !== null && _super.apply(this, arguments) || this;
  95085. }
  95086. /**
  95087. * Gets a string describing the action executed by the current optimization
  95088. * @return description string
  95089. */
  95090. PostProcessesOptimization.prototype.getDescription = function () {
  95091. return "Turning post-processes on/off";
  95092. };
  95093. /**
  95094. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95095. * @param scene defines the current scene where to apply this optimization
  95096. * @param optimizer defines the current optimizer
  95097. * @returns true if everything that can be done was applied
  95098. */
  95099. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  95100. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  95101. return true;
  95102. };
  95103. ;
  95104. return PostProcessesOptimization;
  95105. }(SceneOptimization));
  95106. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  95107. /**
  95108. * Defines an optimization used to turn lens flares off
  95109. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95110. */
  95111. var LensFlaresOptimization = /** @class */ (function (_super) {
  95112. __extends(LensFlaresOptimization, _super);
  95113. function LensFlaresOptimization() {
  95114. return _super !== null && _super.apply(this, arguments) || this;
  95115. }
  95116. /**
  95117. * Gets a string describing the action executed by the current optimization
  95118. * @return description string
  95119. */
  95120. LensFlaresOptimization.prototype.getDescription = function () {
  95121. return "Turning lens flares on/off";
  95122. };
  95123. /**
  95124. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95125. * @param scene defines the current scene where to apply this optimization
  95126. * @param optimizer defines the current optimizer
  95127. * @returns true if everything that can be done was applied
  95128. */
  95129. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  95130. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  95131. return true;
  95132. };
  95133. ;
  95134. return LensFlaresOptimization;
  95135. }(SceneOptimization));
  95136. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  95137. /**
  95138. * Defines an optimization based on user defined callback.
  95139. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95140. */
  95141. var CustomOptimization = /** @class */ (function (_super) {
  95142. __extends(CustomOptimization, _super);
  95143. function CustomOptimization() {
  95144. return _super !== null && _super.apply(this, arguments) || this;
  95145. }
  95146. /**
  95147. * Gets a string describing the action executed by the current optimization
  95148. * @returns description string
  95149. */
  95150. CustomOptimization.prototype.getDescription = function () {
  95151. if (this.onGetDescription) {
  95152. return this.onGetDescription();
  95153. }
  95154. return "Running user defined callback";
  95155. };
  95156. /**
  95157. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95158. * @param scene defines the current scene where to apply this optimization
  95159. * @param optimizer defines the current optimizer
  95160. * @returns true if everything that can be done was applied
  95161. */
  95162. CustomOptimization.prototype.apply = function (scene, optimizer) {
  95163. if (this.onApply) {
  95164. return this.onApply(scene, optimizer);
  95165. }
  95166. return true;
  95167. };
  95168. ;
  95169. return CustomOptimization;
  95170. }(SceneOptimization));
  95171. BABYLON.CustomOptimization = CustomOptimization;
  95172. /**
  95173. * Defines an optimization used to turn particles off
  95174. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95175. */
  95176. var ParticlesOptimization = /** @class */ (function (_super) {
  95177. __extends(ParticlesOptimization, _super);
  95178. function ParticlesOptimization() {
  95179. return _super !== null && _super.apply(this, arguments) || this;
  95180. }
  95181. /**
  95182. * Gets a string describing the action executed by the current optimization
  95183. * @return description string
  95184. */
  95185. ParticlesOptimization.prototype.getDescription = function () {
  95186. return "Turning particles on/off";
  95187. };
  95188. /**
  95189. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95190. * @param scene defines the current scene where to apply this optimization
  95191. * @param optimizer defines the current optimizer
  95192. * @returns true if everything that can be done was applied
  95193. */
  95194. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  95195. scene.particlesEnabled = optimizer.isInImprovementMode;
  95196. return true;
  95197. };
  95198. ;
  95199. return ParticlesOptimization;
  95200. }(SceneOptimization));
  95201. BABYLON.ParticlesOptimization = ParticlesOptimization;
  95202. /**
  95203. * Defines an optimization used to turn render targets off
  95204. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95205. */
  95206. var RenderTargetsOptimization = /** @class */ (function (_super) {
  95207. __extends(RenderTargetsOptimization, _super);
  95208. function RenderTargetsOptimization() {
  95209. return _super !== null && _super.apply(this, arguments) || this;
  95210. }
  95211. /**
  95212. * Gets a string describing the action executed by the current optimization
  95213. * @return description string
  95214. */
  95215. RenderTargetsOptimization.prototype.getDescription = function () {
  95216. return "Turning render targets off";
  95217. };
  95218. /**
  95219. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95220. * @param scene defines the current scene where to apply this optimization
  95221. * @param optimizer defines the current optimizer
  95222. * @returns true if everything that can be done was applied
  95223. */
  95224. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  95225. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  95226. return true;
  95227. };
  95228. ;
  95229. return RenderTargetsOptimization;
  95230. }(SceneOptimization));
  95231. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  95232. /**
  95233. * Defines an optimization used to merge meshes with compatible materials
  95234. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95235. */
  95236. var MergeMeshesOptimization = /** @class */ (function (_super) {
  95237. __extends(MergeMeshesOptimization, _super);
  95238. function MergeMeshesOptimization() {
  95239. var _this = _super !== null && _super.apply(this, arguments) || this;
  95240. _this._canBeMerged = function (abstractMesh) {
  95241. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  95242. return false;
  95243. }
  95244. var mesh = abstractMesh;
  95245. if (!mesh.isVisible || !mesh.isEnabled()) {
  95246. return false;
  95247. }
  95248. if (mesh.instances.length > 0) {
  95249. return false;
  95250. }
  95251. if (mesh.skeleton || mesh.hasLODLevels) {
  95252. return false;
  95253. }
  95254. if (mesh.parent) {
  95255. return false;
  95256. }
  95257. return true;
  95258. };
  95259. return _this;
  95260. }
  95261. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  95262. /**
  95263. * Gets or sets a boolean which defines if optimization octree has to be updated
  95264. */
  95265. get: function () {
  95266. return MergeMeshesOptimization._UpdateSelectionTree;
  95267. },
  95268. /**
  95269. * Gets or sets a boolean which defines if optimization octree has to be updated
  95270. */
  95271. set: function (value) {
  95272. MergeMeshesOptimization._UpdateSelectionTree = value;
  95273. },
  95274. enumerable: true,
  95275. configurable: true
  95276. });
  95277. /**
  95278. * Gets a string describing the action executed by the current optimization
  95279. * @return description string
  95280. */
  95281. MergeMeshesOptimization.prototype.getDescription = function () {
  95282. return "Merging similar meshes together";
  95283. };
  95284. /**
  95285. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95286. * @param scene defines the current scene where to apply this optimization
  95287. * @param optimizer defines the current optimizer
  95288. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  95289. * @returns true if everything that can be done was applied
  95290. */
  95291. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  95292. var globalPool = scene.meshes.slice(0);
  95293. var globalLength = globalPool.length;
  95294. for (var index = 0; index < globalLength; index++) {
  95295. var currentPool = new Array();
  95296. var current = globalPool[index];
  95297. // Checks
  95298. if (!this._canBeMerged(current)) {
  95299. continue;
  95300. }
  95301. currentPool.push(current);
  95302. // Find compatible meshes
  95303. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  95304. var otherMesh = globalPool[subIndex];
  95305. if (!this._canBeMerged(otherMesh)) {
  95306. continue;
  95307. }
  95308. if (otherMesh.material !== current.material) {
  95309. continue;
  95310. }
  95311. if (otherMesh.checkCollisions !== current.checkCollisions) {
  95312. continue;
  95313. }
  95314. currentPool.push(otherMesh);
  95315. globalLength--;
  95316. globalPool.splice(subIndex, 1);
  95317. subIndex--;
  95318. }
  95319. if (currentPool.length < 2) {
  95320. continue;
  95321. }
  95322. // Merge meshes
  95323. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  95324. }
  95325. if (updateSelectionTree != undefined) {
  95326. if (updateSelectionTree) {
  95327. scene.createOrUpdateSelectionOctree();
  95328. }
  95329. }
  95330. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  95331. scene.createOrUpdateSelectionOctree();
  95332. }
  95333. return true;
  95334. };
  95335. ;
  95336. MergeMeshesOptimization._UpdateSelectionTree = false;
  95337. return MergeMeshesOptimization;
  95338. }(SceneOptimization));
  95339. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  95340. /**
  95341. * Defines a list of options used by SceneOptimizer
  95342. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95343. */
  95344. var SceneOptimizerOptions = /** @class */ (function () {
  95345. /**
  95346. * Creates a new list of options used by SceneOptimizer
  95347. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  95348. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  95349. */
  95350. function SceneOptimizerOptions(
  95351. /**
  95352. * Defines the target frame rate to reach (60 by default)
  95353. */
  95354. targetFrameRate,
  95355. /**
  95356. * Defines the interval between two checkes (2000ms by default)
  95357. */
  95358. trackerDuration) {
  95359. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  95360. if (trackerDuration === void 0) { trackerDuration = 2000; }
  95361. this.targetFrameRate = targetFrameRate;
  95362. this.trackerDuration = trackerDuration;
  95363. /**
  95364. * Gets the list of optimizations to apply
  95365. */
  95366. this.optimizations = new Array();
  95367. }
  95368. /**
  95369. * Add a new optimization
  95370. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  95371. * @returns the current SceneOptimizerOptions
  95372. */
  95373. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  95374. this.optimizations.push(optimization);
  95375. return this;
  95376. };
  95377. /**
  95378. * Add a new custom optimization
  95379. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  95380. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  95381. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95382. * @returns the current SceneOptimizerOptions
  95383. */
  95384. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  95385. if (priority === void 0) { priority = 0; }
  95386. var optimization = new CustomOptimization(priority);
  95387. optimization.onApply = onApply;
  95388. optimization.onGetDescription = onGetDescription;
  95389. this.optimizations.push(optimization);
  95390. return this;
  95391. };
  95392. /**
  95393. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  95394. * @param targetFrameRate defines the target frame rate (60 by default)
  95395. * @returns a SceneOptimizerOptions object
  95396. */
  95397. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  95398. var result = new SceneOptimizerOptions(targetFrameRate);
  95399. var priority = 0;
  95400. result.addOptimization(new MergeMeshesOptimization(priority));
  95401. result.addOptimization(new ShadowsOptimization(priority));
  95402. result.addOptimization(new LensFlaresOptimization(priority));
  95403. // Next priority
  95404. priority++;
  95405. result.addOptimization(new PostProcessesOptimization(priority));
  95406. result.addOptimization(new ParticlesOptimization(priority));
  95407. // Next priority
  95408. priority++;
  95409. result.addOptimization(new TextureOptimization(priority, 1024));
  95410. return result;
  95411. };
  95412. /**
  95413. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  95414. * @param targetFrameRate defines the target frame rate (60 by default)
  95415. * @returns a SceneOptimizerOptions object
  95416. */
  95417. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  95418. var result = new SceneOptimizerOptions(targetFrameRate);
  95419. var priority = 0;
  95420. result.addOptimization(new MergeMeshesOptimization(priority));
  95421. result.addOptimization(new ShadowsOptimization(priority));
  95422. result.addOptimization(new LensFlaresOptimization(priority));
  95423. // Next priority
  95424. priority++;
  95425. result.addOptimization(new PostProcessesOptimization(priority));
  95426. result.addOptimization(new ParticlesOptimization(priority));
  95427. // Next priority
  95428. priority++;
  95429. result.addOptimization(new TextureOptimization(priority, 512));
  95430. // Next priority
  95431. priority++;
  95432. result.addOptimization(new RenderTargetsOptimization(priority));
  95433. // Next priority
  95434. priority++;
  95435. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  95436. return result;
  95437. };
  95438. /**
  95439. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  95440. * @param targetFrameRate defines the target frame rate (60 by default)
  95441. * @returns a SceneOptimizerOptions object
  95442. */
  95443. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  95444. var result = new SceneOptimizerOptions(targetFrameRate);
  95445. var priority = 0;
  95446. result.addOptimization(new MergeMeshesOptimization(priority));
  95447. result.addOptimization(new ShadowsOptimization(priority));
  95448. result.addOptimization(new LensFlaresOptimization(priority));
  95449. // Next priority
  95450. priority++;
  95451. result.addOptimization(new PostProcessesOptimization(priority));
  95452. result.addOptimization(new ParticlesOptimization(priority));
  95453. // Next priority
  95454. priority++;
  95455. result.addOptimization(new TextureOptimization(priority, 256));
  95456. // Next priority
  95457. priority++;
  95458. result.addOptimization(new RenderTargetsOptimization(priority));
  95459. // Next priority
  95460. priority++;
  95461. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  95462. return result;
  95463. };
  95464. return SceneOptimizerOptions;
  95465. }());
  95466. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  95467. /**
  95468. * Class used to run optimizations in order to reach a target frame rate
  95469. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95470. */
  95471. var SceneOptimizer = /** @class */ (function () {
  95472. /**
  95473. * Creates a new SceneOptimizer
  95474. * @param scene defines the scene to work on
  95475. * @param options defines the options to use with the SceneOptimizer
  95476. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  95477. * @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)
  95478. */
  95479. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  95480. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  95481. if (improvementMode === void 0) { improvementMode = false; }
  95482. var _this = this;
  95483. this._isRunning = false;
  95484. this._currentPriorityLevel = 0;
  95485. this._targetFrameRate = 60;
  95486. this._trackerDuration = 2000;
  95487. this._currentFrameRate = 0;
  95488. this._improvementMode = false;
  95489. /**
  95490. * Defines an observable called when the optimizer reaches the target frame rate
  95491. */
  95492. this.onSuccessObservable = new BABYLON.Observable();
  95493. /**
  95494. * Defines an observable called when the optimizer enables an optimization
  95495. */
  95496. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  95497. /**
  95498. * Defines an observable called when the optimizer is not able to reach the target frame rate
  95499. */
  95500. this.onFailureObservable = new BABYLON.Observable();
  95501. if (!options) {
  95502. this._options = new SceneOptimizerOptions();
  95503. }
  95504. else {
  95505. this._options = options;
  95506. }
  95507. if (this._options.targetFrameRate) {
  95508. this._targetFrameRate = this._options.targetFrameRate;
  95509. }
  95510. if (this._options.trackerDuration) {
  95511. this._trackerDuration = this._options.trackerDuration;
  95512. }
  95513. if (autoGeneratePriorities) {
  95514. var priority = 0;
  95515. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  95516. var optim = _a[_i];
  95517. optim.priority = priority++;
  95518. }
  95519. }
  95520. this._improvementMode = improvementMode;
  95521. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95522. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  95523. _this._sceneDisposeObserver = null;
  95524. _this.dispose();
  95525. });
  95526. }
  95527. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  95528. /**
  95529. * Gets a boolean indicating if the optimizer is in improvement mode
  95530. */
  95531. get: function () {
  95532. return this._improvementMode;
  95533. },
  95534. enumerable: true,
  95535. configurable: true
  95536. });
  95537. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  95538. /**
  95539. * Gets the current priority level (0 at start)
  95540. */
  95541. get: function () {
  95542. return this._currentPriorityLevel;
  95543. },
  95544. enumerable: true,
  95545. configurable: true
  95546. });
  95547. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  95548. /**
  95549. * Gets the current frame rate checked by the SceneOptimizer
  95550. */
  95551. get: function () {
  95552. return this._currentFrameRate;
  95553. },
  95554. enumerable: true,
  95555. configurable: true
  95556. });
  95557. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  95558. /**
  95559. * Gets or sets the current target frame rate (60 by default)
  95560. */
  95561. get: function () {
  95562. return this._targetFrameRate;
  95563. },
  95564. /**
  95565. * Gets or sets the current target frame rate (60 by default)
  95566. */
  95567. set: function (value) {
  95568. this._targetFrameRate = value;
  95569. },
  95570. enumerable: true,
  95571. configurable: true
  95572. });
  95573. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  95574. /**
  95575. * Gets or sets the current interval between two checks (every 2000ms by default)
  95576. */
  95577. get: function () {
  95578. return this._trackerDuration;
  95579. },
  95580. /**
  95581. * Gets or sets the current interval between two checks (every 2000ms by default)
  95582. */
  95583. set: function (value) {
  95584. this._trackerDuration = value;
  95585. },
  95586. enumerable: true,
  95587. configurable: true
  95588. });
  95589. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  95590. /**
  95591. * Gets the list of active optimizations
  95592. */
  95593. get: function () {
  95594. return this._options.optimizations;
  95595. },
  95596. enumerable: true,
  95597. configurable: true
  95598. });
  95599. /**
  95600. * Stops the current optimizer
  95601. */
  95602. SceneOptimizer.prototype.stop = function () {
  95603. this._isRunning = false;
  95604. };
  95605. /**
  95606. * Reset the optimizer to initial step (current priority level = 0)
  95607. */
  95608. SceneOptimizer.prototype.reset = function () {
  95609. this._currentPriorityLevel = 0;
  95610. };
  95611. /**
  95612. * Start the optimizer. By default it will try to reach a specific framerate
  95613. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  95614. */
  95615. SceneOptimizer.prototype.start = function () {
  95616. var _this = this;
  95617. if (this._isRunning) {
  95618. return;
  95619. }
  95620. this._isRunning = true;
  95621. // Let's wait for the scene to be ready before running our check
  95622. this._scene.executeWhenReady(function () {
  95623. setTimeout(function () {
  95624. _this._checkCurrentState();
  95625. }, _this._trackerDuration);
  95626. });
  95627. };
  95628. SceneOptimizer.prototype._checkCurrentState = function () {
  95629. var _this = this;
  95630. if (!this._isRunning) {
  95631. return;
  95632. }
  95633. var scene = this._scene;
  95634. var options = this._options;
  95635. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  95636. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  95637. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  95638. this._isRunning = false;
  95639. this.onSuccessObservable.notifyObservers(this);
  95640. return;
  95641. }
  95642. // Apply current level of optimizations
  95643. var allDone = true;
  95644. var noOptimizationApplied = true;
  95645. for (var index = 0; index < options.optimizations.length; index++) {
  95646. var optimization = options.optimizations[index];
  95647. if (optimization.priority === this._currentPriorityLevel) {
  95648. noOptimizationApplied = false;
  95649. allDone = allDone && optimization.apply(scene, this);
  95650. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  95651. }
  95652. }
  95653. // If no optimization was applied, this is a failure :(
  95654. if (noOptimizationApplied) {
  95655. this._isRunning = false;
  95656. this.onFailureObservable.notifyObservers(this);
  95657. return;
  95658. }
  95659. // If all optimizations were done, move to next level
  95660. if (allDone) {
  95661. this._currentPriorityLevel++;
  95662. }
  95663. // Let's the system running for a specific amount of time before checking FPS
  95664. scene.executeWhenReady(function () {
  95665. setTimeout(function () {
  95666. _this._checkCurrentState();
  95667. }, _this._trackerDuration);
  95668. });
  95669. };
  95670. /**
  95671. * Release all resources
  95672. */
  95673. SceneOptimizer.prototype.dispose = function () {
  95674. this.stop();
  95675. this.onSuccessObservable.clear();
  95676. this.onFailureObservable.clear();
  95677. this.onNewOptimizationAppliedObservable.clear();
  95678. if (this._sceneDisposeObserver) {
  95679. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  95680. }
  95681. };
  95682. /**
  95683. * Helper function to create a SceneOptimizer with one single line of code
  95684. * @param scene defines the scene to work on
  95685. * @param options defines the options to use with the SceneOptimizer
  95686. * @param onSuccess defines a callback to call on success
  95687. * @param onFailure defines a callback to call on failure
  95688. * @returns the new SceneOptimizer object
  95689. */
  95690. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  95691. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  95692. if (onSuccess) {
  95693. optimizer.onSuccessObservable.add(function () {
  95694. onSuccess();
  95695. });
  95696. }
  95697. if (onFailure) {
  95698. optimizer.onFailureObservable.add(function () {
  95699. onFailure();
  95700. });
  95701. }
  95702. optimizer.start();
  95703. return optimizer;
  95704. };
  95705. return SceneOptimizer;
  95706. }());
  95707. BABYLON.SceneOptimizer = SceneOptimizer;
  95708. })(BABYLON || (BABYLON = {}));
  95709. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  95710. var BABYLON;
  95711. (function (BABYLON) {
  95712. var OutlineRenderer = /** @class */ (function () {
  95713. function OutlineRenderer(scene) {
  95714. this.zOffset = 1;
  95715. this._scene = scene;
  95716. }
  95717. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  95718. var _this = this;
  95719. if (useOverlay === void 0) { useOverlay = false; }
  95720. var scene = this._scene;
  95721. var engine = this._scene.getEngine();
  95722. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95723. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  95724. return;
  95725. }
  95726. var mesh = subMesh.getRenderingMesh();
  95727. var material = subMesh.getMaterial();
  95728. if (!material || !scene.activeCamera) {
  95729. return;
  95730. }
  95731. engine.enableEffect(this._effect);
  95732. // Logarithmic depth
  95733. if (material.useLogarithmicDepth) {
  95734. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  95735. }
  95736. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  95737. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  95738. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  95739. // Bones
  95740. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95741. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95742. }
  95743. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  95744. // Alpha test
  95745. if (material && material.needAlphaTesting()) {
  95746. var alphaTexture = material.getAlphaTestTexture();
  95747. if (alphaTexture) {
  95748. this._effect.setTexture("diffuseSampler", alphaTexture);
  95749. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  95750. }
  95751. }
  95752. engine.setZOffset(-this.zOffset);
  95753. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  95754. engine.setZOffset(0);
  95755. };
  95756. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  95757. var defines = [];
  95758. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  95759. var mesh = subMesh.getMesh();
  95760. var material = subMesh.getMaterial();
  95761. if (material) {
  95762. // Alpha test
  95763. if (material.needAlphaTesting()) {
  95764. defines.push("#define ALPHATEST");
  95765. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95766. attribs.push(BABYLON.VertexBuffer.UVKind);
  95767. defines.push("#define UV1");
  95768. }
  95769. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  95770. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95771. defines.push("#define UV2");
  95772. }
  95773. }
  95774. //Logarithmic depth
  95775. if (material.useLogarithmicDepth) {
  95776. defines.push("#define LOGARITHMICDEPTH");
  95777. }
  95778. }
  95779. // Bones
  95780. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  95781. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  95782. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  95783. if (mesh.numBoneInfluencers > 4) {
  95784. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95785. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95786. }
  95787. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95788. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  95789. }
  95790. else {
  95791. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95792. }
  95793. // Instances
  95794. if (useInstances) {
  95795. defines.push("#define INSTANCES");
  95796. attribs.push("world0");
  95797. attribs.push("world1");
  95798. attribs.push("world2");
  95799. attribs.push("world3");
  95800. }
  95801. // Get correct effect
  95802. var join = defines.join("\n");
  95803. if (this._cachedDefines !== join) {
  95804. this._cachedDefines = join;
  95805. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  95806. }
  95807. return this._effect.isReady();
  95808. };
  95809. return OutlineRenderer;
  95810. }());
  95811. BABYLON.OutlineRenderer = OutlineRenderer;
  95812. })(BABYLON || (BABYLON = {}));
  95813. //# sourceMappingURL=babylon.outlineRenderer.js.map
  95814. var BABYLON;
  95815. (function (BABYLON) {
  95816. var FaceAdjacencies = /** @class */ (function () {
  95817. function FaceAdjacencies() {
  95818. this.edges = new Array();
  95819. this.edgesConnectedCount = 0;
  95820. }
  95821. return FaceAdjacencies;
  95822. }());
  95823. var EdgesRenderer = /** @class */ (function () {
  95824. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  95825. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  95826. if (epsilon === void 0) { epsilon = 0.95; }
  95827. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  95828. this.edgesWidthScalerForOrthographic = 1000.0;
  95829. this.edgesWidthScalerForPerspective = 50.0;
  95830. this._linesPositions = new Array();
  95831. this._linesNormals = new Array();
  95832. this._linesIndices = new Array();
  95833. this._buffers = {};
  95834. this._checkVerticesInsteadOfIndices = false;
  95835. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  95836. this.isEnabled = true;
  95837. this._source = source;
  95838. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  95839. this._epsilon = epsilon;
  95840. this._prepareRessources();
  95841. this._generateEdgesLines();
  95842. }
  95843. EdgesRenderer.prototype._prepareRessources = function () {
  95844. if (this._lineShader) {
  95845. return;
  95846. }
  95847. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  95848. attributes: ["position", "normal"],
  95849. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  95850. });
  95851. this._lineShader.disableDepthWrite = true;
  95852. this._lineShader.backFaceCulling = false;
  95853. };
  95854. EdgesRenderer.prototype._rebuild = function () {
  95855. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95856. if (buffer) {
  95857. buffer._rebuild();
  95858. }
  95859. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95860. if (buffer) {
  95861. buffer._rebuild();
  95862. }
  95863. var scene = this._source.getScene();
  95864. var engine = scene.getEngine();
  95865. this._ib = engine.createIndexBuffer(this._linesIndices);
  95866. };
  95867. EdgesRenderer.prototype.dispose = function () {
  95868. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95869. if (buffer) {
  95870. buffer.dispose();
  95871. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  95872. }
  95873. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95874. if (buffer) {
  95875. buffer.dispose();
  95876. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  95877. }
  95878. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  95879. this._lineShader.dispose();
  95880. };
  95881. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  95882. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  95883. return 0;
  95884. }
  95885. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  95886. return 1;
  95887. }
  95888. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  95889. return 2;
  95890. }
  95891. return -1;
  95892. };
  95893. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  95894. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  95895. return 0;
  95896. }
  95897. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  95898. return 1;
  95899. }
  95900. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  95901. return 2;
  95902. }
  95903. return -1;
  95904. };
  95905. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  95906. var needToCreateLine;
  95907. if (edge === undefined) {
  95908. needToCreateLine = true;
  95909. }
  95910. else {
  95911. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  95912. needToCreateLine = dotProduct < this._epsilon;
  95913. }
  95914. if (needToCreateLine) {
  95915. var offset = this._linesPositions.length / 3;
  95916. var normal = p0.subtract(p1);
  95917. normal.normalize();
  95918. // Positions
  95919. this._linesPositions.push(p0.x);
  95920. this._linesPositions.push(p0.y);
  95921. this._linesPositions.push(p0.z);
  95922. this._linesPositions.push(p0.x);
  95923. this._linesPositions.push(p0.y);
  95924. this._linesPositions.push(p0.z);
  95925. this._linesPositions.push(p1.x);
  95926. this._linesPositions.push(p1.y);
  95927. this._linesPositions.push(p1.z);
  95928. this._linesPositions.push(p1.x);
  95929. this._linesPositions.push(p1.y);
  95930. this._linesPositions.push(p1.z);
  95931. // Normals
  95932. this._linesNormals.push(p1.x);
  95933. this._linesNormals.push(p1.y);
  95934. this._linesNormals.push(p1.z);
  95935. this._linesNormals.push(-1);
  95936. this._linesNormals.push(p1.x);
  95937. this._linesNormals.push(p1.y);
  95938. this._linesNormals.push(p1.z);
  95939. this._linesNormals.push(1);
  95940. this._linesNormals.push(p0.x);
  95941. this._linesNormals.push(p0.y);
  95942. this._linesNormals.push(p0.z);
  95943. this._linesNormals.push(-1);
  95944. this._linesNormals.push(p0.x);
  95945. this._linesNormals.push(p0.y);
  95946. this._linesNormals.push(p0.z);
  95947. this._linesNormals.push(1);
  95948. // Indices
  95949. this._linesIndices.push(offset);
  95950. this._linesIndices.push(offset + 1);
  95951. this._linesIndices.push(offset + 2);
  95952. this._linesIndices.push(offset);
  95953. this._linesIndices.push(offset + 2);
  95954. this._linesIndices.push(offset + 3);
  95955. }
  95956. };
  95957. EdgesRenderer.prototype._generateEdgesLines = function () {
  95958. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  95959. var indices = this._source.getIndices();
  95960. if (!indices || !positions) {
  95961. return;
  95962. }
  95963. // First let's find adjacencies
  95964. var adjacencies = new Array();
  95965. var faceNormals = new Array();
  95966. var index;
  95967. var faceAdjacencies;
  95968. // Prepare faces
  95969. for (index = 0; index < indices.length; index += 3) {
  95970. faceAdjacencies = new FaceAdjacencies();
  95971. var p0Index = indices[index];
  95972. var p1Index = indices[index + 1];
  95973. var p2Index = indices[index + 2];
  95974. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  95975. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  95976. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  95977. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  95978. faceNormal.normalize();
  95979. faceNormals.push(faceNormal);
  95980. adjacencies.push(faceAdjacencies);
  95981. }
  95982. // Scan
  95983. for (index = 0; index < adjacencies.length; index++) {
  95984. faceAdjacencies = adjacencies[index];
  95985. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  95986. var otherFaceAdjacencies = adjacencies[otherIndex];
  95987. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  95988. break;
  95989. }
  95990. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  95991. continue;
  95992. }
  95993. var otherP0 = indices[otherIndex * 3];
  95994. var otherP1 = indices[otherIndex * 3 + 1];
  95995. var otherP2 = indices[otherIndex * 3 + 2];
  95996. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  95997. var otherEdgeIndex = 0;
  95998. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  95999. continue;
  96000. }
  96001. switch (edgeIndex) {
  96002. case 0:
  96003. if (this._checkVerticesInsteadOfIndices) {
  96004. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96005. }
  96006. else {
  96007. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  96008. }
  96009. break;
  96010. case 1:
  96011. if (this._checkVerticesInsteadOfIndices) {
  96012. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96013. }
  96014. else {
  96015. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  96016. }
  96017. break;
  96018. case 2:
  96019. if (this._checkVerticesInsteadOfIndices) {
  96020. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96021. }
  96022. else {
  96023. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  96024. }
  96025. break;
  96026. }
  96027. if (otherEdgeIndex === -1) {
  96028. continue;
  96029. }
  96030. faceAdjacencies.edges[edgeIndex] = otherIndex;
  96031. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  96032. faceAdjacencies.edgesConnectedCount++;
  96033. otherFaceAdjacencies.edgesConnectedCount++;
  96034. if (faceAdjacencies.edgesConnectedCount === 3) {
  96035. break;
  96036. }
  96037. }
  96038. }
  96039. }
  96040. // Create lines
  96041. for (index = 0; index < adjacencies.length; index++) {
  96042. // 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
  96043. var current = adjacencies[index];
  96044. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  96045. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  96046. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  96047. }
  96048. // Merge into a single mesh
  96049. var engine = this._source.getScene().getEngine();
  96050. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  96051. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  96052. this._ib = engine.createIndexBuffer(this._linesIndices);
  96053. this._indicesCount = this._linesIndices.length;
  96054. };
  96055. EdgesRenderer.prototype.render = function () {
  96056. var scene = this._source.getScene();
  96057. if (!this._lineShader.isReady() || !scene.activeCamera) {
  96058. return;
  96059. }
  96060. var engine = scene.getEngine();
  96061. this._lineShader._preBind();
  96062. // VBOs
  96063. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  96064. scene.resetCachedMaterial();
  96065. this._lineShader.setColor4("color", this._source.edgesColor);
  96066. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  96067. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  96068. }
  96069. else {
  96070. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  96071. }
  96072. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  96073. this._lineShader.bind(this._source.getWorldMatrix());
  96074. // Draw order
  96075. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  96076. this._lineShader.unbind();
  96077. engine.setDepthWrite(true);
  96078. };
  96079. return EdgesRenderer;
  96080. }());
  96081. BABYLON.EdgesRenderer = EdgesRenderer;
  96082. })(BABYLON || (BABYLON = {}));
  96083. //# sourceMappingURL=babylon.edgesRenderer.js.map
  96084. var BABYLON;
  96085. (function (BABYLON) {
  96086. // Adds the parser to the scene parsers.
  96087. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  96088. if (parsedData.effectLayers) {
  96089. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  96090. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  96091. container.effectLayers.push(effectLayer);
  96092. }
  96093. }
  96094. });
  96095. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  96096. var index = this.effectLayers.indexOf(toRemove);
  96097. if (index !== -1) {
  96098. this.effectLayers.splice(index, 1);
  96099. }
  96100. return index;
  96101. };
  96102. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  96103. this.effectLayers.push(newEffectLayer);
  96104. };
  96105. /**
  96106. * Defines the layer scene component responsible to manage any effect layers
  96107. * in a given scene.
  96108. */
  96109. var EffectLayerSceneComponent = /** @class */ (function () {
  96110. /**
  96111. * Creates a new instance of the component for the given scene
  96112. * @param scene Defines the scene to register the component in
  96113. */
  96114. function EffectLayerSceneComponent(scene) {
  96115. /**
  96116. * The component name helpfull to identify the component in the list of scene components.
  96117. */
  96118. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  96119. this._renderEffects = false;
  96120. this._needStencil = false;
  96121. this._previousStencilState = false;
  96122. this.scene = scene;
  96123. this._engine = scene.getEngine();
  96124. scene.effectLayers = new Array();
  96125. }
  96126. /**
  96127. * Registers the component in a given scene
  96128. */
  96129. EffectLayerSceneComponent.prototype.register = function () {
  96130. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  96131. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  96132. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  96133. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  96134. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  96135. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  96136. };
  96137. /**
  96138. * Rebuilds the elements related to this component in case of
  96139. * context lost for instance.
  96140. */
  96141. EffectLayerSceneComponent.prototype.rebuild = function () {
  96142. var layers = this.scene.effectLayers;
  96143. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  96144. var effectLayer = layers_1[_i];
  96145. effectLayer._rebuild();
  96146. }
  96147. };
  96148. /**
  96149. * Serializes the component data to the specified json object
  96150. * @param serializationObject The object to serialize to
  96151. */
  96152. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  96153. // Effect layers
  96154. serializationObject.effectLayers = [];
  96155. var layers = this.scene.effectLayers;
  96156. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  96157. var effectLayer = layers_2[_i];
  96158. if (effectLayer.serialize) {
  96159. serializationObject.effectLayers.push(effectLayer.serialize());
  96160. }
  96161. }
  96162. };
  96163. /**
  96164. * Adds all the element from the container to the scene
  96165. * @param container the container holding the elements
  96166. */
  96167. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  96168. var _this = this;
  96169. if (!container.effectLayers) {
  96170. return;
  96171. }
  96172. container.effectLayers.forEach(function (o) {
  96173. _this.scene.addEffectLayer(o);
  96174. });
  96175. };
  96176. /**
  96177. * Removes all the elements in the container from the scene
  96178. * @param container contains the elements to remove
  96179. */
  96180. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  96181. var _this = this;
  96182. if (!container.effectLayers) {
  96183. return;
  96184. }
  96185. container.effectLayers.forEach(function (o) {
  96186. _this.scene.removeEffectLayer(o);
  96187. });
  96188. };
  96189. /**
  96190. * Disposes the component and the associated ressources.
  96191. */
  96192. EffectLayerSceneComponent.prototype.dispose = function () {
  96193. var layers = this.scene.effectLayers;
  96194. while (layers.length) {
  96195. layers[0].dispose();
  96196. }
  96197. };
  96198. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  96199. var layers = this.scene.effectLayers;
  96200. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  96201. var layer = layers_3[_i];
  96202. if (!layer.hasMesh(mesh)) {
  96203. continue;
  96204. }
  96205. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  96206. var subMesh = _b[_a];
  96207. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  96208. return false;
  96209. }
  96210. }
  96211. }
  96212. return true;
  96213. };
  96214. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  96215. this._renderEffects = false;
  96216. this._needStencil = false;
  96217. var layers = this.scene.effectLayers;
  96218. if (layers && layers.length > 0) {
  96219. this._previousStencilState = this._engine.getStencilBuffer();
  96220. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  96221. var effectLayer = layers_4[_i];
  96222. if (effectLayer.shouldRender() &&
  96223. (!effectLayer.camera ||
  96224. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  96225. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  96226. this._renderEffects = true;
  96227. this._needStencil = this._needStencil || effectLayer.needStencil();
  96228. var renderTarget = effectLayer._mainTexture;
  96229. if (renderTarget._shouldRender()) {
  96230. this.scene.incrementRenderId();
  96231. renderTarget.render(false, false);
  96232. }
  96233. }
  96234. }
  96235. this.scene.incrementRenderId();
  96236. }
  96237. };
  96238. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  96239. // Activate effect Layer stencil
  96240. if (this._needStencil) {
  96241. this._engine.setStencilBuffer(true);
  96242. }
  96243. };
  96244. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  96245. // Restore effect Layer stencil
  96246. if (this._needStencil) {
  96247. this._engine.setStencilBuffer(this._previousStencilState);
  96248. }
  96249. };
  96250. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  96251. if (this._renderEffects) {
  96252. this._engine.setDepthBuffer(false);
  96253. var layers = this.scene.effectLayers;
  96254. for (var i = 0; i < layers.length; i++) {
  96255. var effectLayer = layers[i];
  96256. if (effectLayer.renderingGroupId === renderingGroupId) {
  96257. if (effectLayer.shouldRender()) {
  96258. effectLayer.render();
  96259. }
  96260. }
  96261. }
  96262. this._engine.setDepthBuffer(true);
  96263. }
  96264. };
  96265. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  96266. if (this._renderEffects) {
  96267. this._draw(-1);
  96268. }
  96269. };
  96270. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  96271. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  96272. this._draw(index);
  96273. }
  96274. };
  96275. return EffectLayerSceneComponent;
  96276. }());
  96277. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  96278. })(BABYLON || (BABYLON = {}));
  96279. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  96280. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96281. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96282. s = arguments[i];
  96283. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96284. t[p] = s[p];
  96285. }
  96286. return t;
  96287. };
  96288. var BABYLON;
  96289. (function (BABYLON) {
  96290. /**
  96291. * The effect layer Helps adding post process effect blended with the main pass.
  96292. *
  96293. * This can be for instance use to generate glow or higlight effects on the scene.
  96294. *
  96295. * The effect layer class can not be used directly and is intented to inherited from to be
  96296. * customized per effects.
  96297. */
  96298. var EffectLayer = /** @class */ (function () {
  96299. /**
  96300. * Instantiates a new effect Layer and references it in the scene.
  96301. * @param name The name of the layer
  96302. * @param scene The scene to use the layer in
  96303. */
  96304. function EffectLayer(
  96305. /** The Friendly of the effect in the scene */
  96306. name, scene) {
  96307. this._vertexBuffers = {};
  96308. this._maxSize = 0;
  96309. this._mainTextureDesiredSize = { width: 0, height: 0 };
  96310. this._shouldRender = true;
  96311. this._postProcesses = [];
  96312. this._textures = [];
  96313. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  96314. /**
  96315. * The clear color of the texture used to generate the glow map.
  96316. */
  96317. this.neutralColor = new BABYLON.Color4();
  96318. /**
  96319. * Specifies wether the highlight layer is enabled or not.
  96320. */
  96321. this.isEnabled = true;
  96322. /**
  96323. * An event triggered when the effect layer has been disposed.
  96324. */
  96325. this.onDisposeObservable = new BABYLON.Observable();
  96326. /**
  96327. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  96328. */
  96329. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  96330. /**
  96331. * An event triggered when the generated texture is being merged in the scene.
  96332. */
  96333. this.onBeforeComposeObservable = new BABYLON.Observable();
  96334. /**
  96335. * An event triggered when the generated texture has been merged in the scene.
  96336. */
  96337. this.onAfterComposeObservable = new BABYLON.Observable();
  96338. /**
  96339. * An event triggered when the efffect layer changes its size.
  96340. */
  96341. this.onSizeChangedObservable = new BABYLON.Observable();
  96342. this.name = name;
  96343. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96344. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  96345. if (!component) {
  96346. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  96347. this._scene._addComponent(component);
  96348. }
  96349. this._engine = this._scene.getEngine();
  96350. this._maxSize = this._engine.getCaps().maxTextureSize;
  96351. this._scene.effectLayers.push(this);
  96352. // Generate Buffers
  96353. this._generateIndexBuffer();
  96354. this._genrateVertexBuffer();
  96355. }
  96356. Object.defineProperty(EffectLayer.prototype, "camera", {
  96357. /**
  96358. * Gets the camera attached to the layer.
  96359. */
  96360. get: function () {
  96361. return this._effectLayerOptions.camera;
  96362. },
  96363. enumerable: true,
  96364. configurable: true
  96365. });
  96366. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  96367. /**
  96368. * Gets the rendering group id the layer should render in.
  96369. */
  96370. get: function () {
  96371. return this._effectLayerOptions.renderingGroupId;
  96372. },
  96373. enumerable: true,
  96374. configurable: true
  96375. });
  96376. /**
  96377. * Initializes the effect layer with the required options.
  96378. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  96379. */
  96380. EffectLayer.prototype._init = function (options) {
  96381. // Adapt options
  96382. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  96383. this._setMainTextureSize();
  96384. this._createMainTexture();
  96385. this._createTextureAndPostProcesses();
  96386. this._mergeEffect = this._createMergeEffect();
  96387. };
  96388. /**
  96389. * Generates the index buffer of the full screen quad blending to the main canvas.
  96390. */
  96391. EffectLayer.prototype._generateIndexBuffer = function () {
  96392. // Indices
  96393. var indices = [];
  96394. indices.push(0);
  96395. indices.push(1);
  96396. indices.push(2);
  96397. indices.push(0);
  96398. indices.push(2);
  96399. indices.push(3);
  96400. this._indexBuffer = this._engine.createIndexBuffer(indices);
  96401. };
  96402. /**
  96403. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  96404. */
  96405. EffectLayer.prototype._genrateVertexBuffer = function () {
  96406. // VBO
  96407. var vertices = [];
  96408. vertices.push(1, 1);
  96409. vertices.push(-1, 1);
  96410. vertices.push(-1, -1);
  96411. vertices.push(1, -1);
  96412. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96413. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96414. };
  96415. /**
  96416. * Sets the main texture desired size which is the closest power of two
  96417. * of the engine canvas size.
  96418. */
  96419. EffectLayer.prototype._setMainTextureSize = function () {
  96420. if (this._effectLayerOptions.mainTextureFixedSize) {
  96421. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  96422. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  96423. }
  96424. else {
  96425. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  96426. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  96427. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  96428. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  96429. }
  96430. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  96431. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  96432. };
  96433. /**
  96434. * Creates the main texture for the effect layer.
  96435. */
  96436. EffectLayer.prototype._createMainTexture = function () {
  96437. var _this = this;
  96438. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  96439. width: this._mainTextureDesiredSize.width,
  96440. height: this._mainTextureDesiredSize.height
  96441. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96442. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  96443. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96444. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96445. this._mainTexture.anisotropicFilteringLevel = 1;
  96446. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96447. this._mainTexture.renderParticles = false;
  96448. this._mainTexture.renderList = null;
  96449. this._mainTexture.ignoreCameraViewport = true;
  96450. // Custom render function
  96451. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  96452. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  96453. var index;
  96454. var engine = _this._scene.getEngine();
  96455. if (depthOnlySubMeshes.length) {
  96456. engine.setColorWrite(false);
  96457. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  96458. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  96459. }
  96460. engine.setColorWrite(true);
  96461. }
  96462. for (index = 0; index < opaqueSubMeshes.length; index++) {
  96463. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  96464. }
  96465. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  96466. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  96467. }
  96468. for (index = 0; index < transparentSubMeshes.length; index++) {
  96469. _this._renderSubMesh(transparentSubMeshes.data[index]);
  96470. }
  96471. };
  96472. this._mainTexture.onClearObservable.add(function (engine) {
  96473. engine.clear(_this.neutralColor, true, true, true);
  96474. });
  96475. };
  96476. /**
  96477. * Checks for the readiness of the element composing the layer.
  96478. * @param subMesh the mesh to check for
  96479. * @param useInstances specify wether or not to use instances to render the mesh
  96480. * @param emissiveTexture the associated emissive texture used to generate the glow
  96481. * @return true if ready otherwise, false
  96482. */
  96483. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  96484. var material = subMesh.getMaterial();
  96485. if (!material) {
  96486. return false;
  96487. }
  96488. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  96489. return false;
  96490. }
  96491. var defines = [];
  96492. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96493. var mesh = subMesh.getMesh();
  96494. var uv1 = false;
  96495. var uv2 = false;
  96496. // Alpha test
  96497. if (material && material.needAlphaTesting()) {
  96498. var alphaTexture = material.getAlphaTestTexture();
  96499. if (alphaTexture) {
  96500. defines.push("#define ALPHATEST");
  96501. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96502. alphaTexture.coordinatesIndex === 1) {
  96503. defines.push("#define DIFFUSEUV2");
  96504. uv2 = true;
  96505. }
  96506. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96507. defines.push("#define DIFFUSEUV1");
  96508. uv1 = true;
  96509. }
  96510. }
  96511. }
  96512. // Emissive
  96513. if (emissiveTexture) {
  96514. defines.push("#define EMISSIVE");
  96515. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96516. emissiveTexture.coordinatesIndex === 1) {
  96517. defines.push("#define EMISSIVEUV2");
  96518. uv2 = true;
  96519. }
  96520. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96521. defines.push("#define EMISSIVEUV1");
  96522. uv1 = true;
  96523. }
  96524. }
  96525. if (uv1) {
  96526. attribs.push(BABYLON.VertexBuffer.UVKind);
  96527. defines.push("#define UV1");
  96528. }
  96529. if (uv2) {
  96530. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96531. defines.push("#define UV2");
  96532. }
  96533. // Bones
  96534. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96535. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96536. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96537. if (mesh.numBoneInfluencers > 4) {
  96538. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96539. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96540. }
  96541. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96542. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  96543. }
  96544. else {
  96545. defines.push("#define NUM_BONE_INFLUENCERS 0");
  96546. }
  96547. // Morph targets
  96548. var manager = mesh.morphTargetManager;
  96549. var morphInfluencers = 0;
  96550. if (manager) {
  96551. if (manager.numInfluencers > 0) {
  96552. defines.push("#define MORPHTARGETS");
  96553. morphInfluencers = manager.numInfluencers;
  96554. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  96555. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  96556. }
  96557. }
  96558. // Instances
  96559. if (useInstances) {
  96560. defines.push("#define INSTANCES");
  96561. attribs.push("world0");
  96562. attribs.push("world1");
  96563. attribs.push("world2");
  96564. attribs.push("world3");
  96565. }
  96566. // Get correct effect
  96567. var join = defines.join("\n");
  96568. if (this._cachedDefines !== join) {
  96569. this._cachedDefines = join;
  96570. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  96571. }
  96572. return this._effectLayerMapGenerationEffect.isReady();
  96573. };
  96574. /**
  96575. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  96576. */
  96577. EffectLayer.prototype.render = function () {
  96578. var currentEffect = this._mergeEffect;
  96579. // Check
  96580. if (!currentEffect.isReady())
  96581. return;
  96582. for (var i = 0; i < this._postProcesses.length; i++) {
  96583. if (!this._postProcesses[i].isReady()) {
  96584. return;
  96585. }
  96586. }
  96587. var engine = this._scene.getEngine();
  96588. this.onBeforeComposeObservable.notifyObservers(this);
  96589. // Render
  96590. engine.enableEffect(currentEffect);
  96591. engine.setState(false);
  96592. // VBOs
  96593. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96594. // Cache
  96595. var previousAlphaMode = engine.getAlphaMode();
  96596. // Go Blend.
  96597. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  96598. // Blends the map on the main canvas.
  96599. this._internalRender(currentEffect);
  96600. // Restore Alpha
  96601. engine.setAlphaMode(previousAlphaMode);
  96602. this.onAfterComposeObservable.notifyObservers(this);
  96603. // Handle size changes.
  96604. var size = this._mainTexture.getSize();
  96605. this._setMainTextureSize();
  96606. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  96607. // Recreate RTT and post processes on size change.
  96608. this.onSizeChangedObservable.notifyObservers(this);
  96609. this._disposeTextureAndPostProcesses();
  96610. this._createMainTexture();
  96611. this._createTextureAndPostProcesses();
  96612. }
  96613. };
  96614. /**
  96615. * Determine if a given mesh will be used in the current effect.
  96616. * @param mesh mesh to test
  96617. * @returns true if the mesh will be used
  96618. */
  96619. EffectLayer.prototype.hasMesh = function (mesh) {
  96620. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  96621. return true;
  96622. }
  96623. return false;
  96624. };
  96625. /**
  96626. * Returns true if the layer contains information to display, otherwise false.
  96627. * @returns true if the glow layer should be rendered
  96628. */
  96629. EffectLayer.prototype.shouldRender = function () {
  96630. return this.isEnabled && this._shouldRender;
  96631. };
  96632. /**
  96633. * Returns true if the mesh should render, otherwise false.
  96634. * @param mesh The mesh to render
  96635. * @returns true if it should render otherwise false
  96636. */
  96637. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  96638. return true;
  96639. };
  96640. /**
  96641. * Returns true if the mesh should render, otherwise false.
  96642. * @param mesh The mesh to render
  96643. * @returns true if it should render otherwise false
  96644. */
  96645. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  96646. return true;
  96647. };
  96648. /**
  96649. * Renders the submesh passed in parameter to the generation map.
  96650. */
  96651. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  96652. var _this = this;
  96653. if (!this.shouldRender()) {
  96654. return;
  96655. }
  96656. var material = subMesh.getMaterial();
  96657. var mesh = subMesh.getRenderingMesh();
  96658. var scene = this._scene;
  96659. var engine = scene.getEngine();
  96660. if (!material) {
  96661. return;
  96662. }
  96663. // Do not block in blend mode.
  96664. if (material.needAlphaBlendingForMesh(mesh)) {
  96665. return;
  96666. }
  96667. // Culling
  96668. engine.setState(material.backFaceCulling);
  96669. // Managing instances
  96670. var batch = mesh._getInstancesRenderList(subMesh._id);
  96671. if (batch.mustReturn) {
  96672. return;
  96673. }
  96674. // Early Exit per mesh
  96675. if (!this._shouldRenderMesh(mesh)) {
  96676. return;
  96677. }
  96678. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  96679. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  96680. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  96681. engine.enableEffect(this._effectLayerMapGenerationEffect);
  96682. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  96683. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  96684. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  96685. // Alpha test
  96686. if (material && material.needAlphaTesting()) {
  96687. var alphaTexture = material.getAlphaTestTexture();
  96688. if (alphaTexture) {
  96689. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  96690. var textureMatrix = alphaTexture.getTextureMatrix();
  96691. if (textureMatrix) {
  96692. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  96693. }
  96694. }
  96695. }
  96696. // Glow emissive only
  96697. if (this._emissiveTextureAndColor.texture) {
  96698. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  96699. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  96700. }
  96701. // Bones
  96702. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  96703. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  96704. }
  96705. // Morph targets
  96706. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  96707. // Draw
  96708. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  96709. }
  96710. else {
  96711. // Need to reset refresh rate of the main map
  96712. this._mainTexture.resetRefreshCounter();
  96713. }
  96714. };
  96715. /**
  96716. * Rebuild the required buffers.
  96717. * @hidden Internal use only.
  96718. */
  96719. EffectLayer.prototype._rebuild = function () {
  96720. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96721. if (vb) {
  96722. vb._rebuild();
  96723. }
  96724. this._generateIndexBuffer();
  96725. };
  96726. /**
  96727. * Dispose only the render target textures and post process.
  96728. */
  96729. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  96730. this._mainTexture.dispose();
  96731. for (var i = 0; i < this._postProcesses.length; i++) {
  96732. if (this._postProcesses[i]) {
  96733. this._postProcesses[i].dispose();
  96734. }
  96735. }
  96736. this._postProcesses = [];
  96737. for (var i = 0; i < this._textures.length; i++) {
  96738. if (this._textures[i]) {
  96739. this._textures[i].dispose();
  96740. }
  96741. }
  96742. this._textures = [];
  96743. };
  96744. /**
  96745. * Dispose the highlight layer and free resources.
  96746. */
  96747. EffectLayer.prototype.dispose = function () {
  96748. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96749. if (vertexBuffer) {
  96750. vertexBuffer.dispose();
  96751. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96752. }
  96753. if (this._indexBuffer) {
  96754. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96755. this._indexBuffer = null;
  96756. }
  96757. // Clean textures and post processes
  96758. this._disposeTextureAndPostProcesses();
  96759. // Remove from scene
  96760. var index = this._scene.effectLayers.indexOf(this, 0);
  96761. if (index > -1) {
  96762. this._scene.effectLayers.splice(index, 1);
  96763. }
  96764. // Callback
  96765. this.onDisposeObservable.notifyObservers(this);
  96766. this.onDisposeObservable.clear();
  96767. this.onBeforeRenderMainTextureObservable.clear();
  96768. this.onBeforeComposeObservable.clear();
  96769. this.onAfterComposeObservable.clear();
  96770. this.onSizeChangedObservable.clear();
  96771. };
  96772. /**
  96773. * Gets the class name of the effect layer
  96774. * @returns the string with the class name of the effect layer
  96775. */
  96776. EffectLayer.prototype.getClassName = function () {
  96777. return "EffectLayer";
  96778. };
  96779. /**
  96780. * Creates an effect layer from parsed effect layer data
  96781. * @param parsedEffectLayer defines effect layer data
  96782. * @param scene defines the current scene
  96783. * @param rootUrl defines the root URL containing the effect layer information
  96784. * @returns a parsed effect Layer
  96785. */
  96786. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  96787. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  96788. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  96789. };
  96790. __decorate([
  96791. BABYLON.serialize()
  96792. ], EffectLayer.prototype, "name", void 0);
  96793. __decorate([
  96794. BABYLON.serializeAsColor4()
  96795. ], EffectLayer.prototype, "neutralColor", void 0);
  96796. __decorate([
  96797. BABYLON.serialize()
  96798. ], EffectLayer.prototype, "isEnabled", void 0);
  96799. __decorate([
  96800. BABYLON.serializeAsCameraReference()
  96801. ], EffectLayer.prototype, "camera", null);
  96802. __decorate([
  96803. BABYLON.serialize()
  96804. ], EffectLayer.prototype, "renderingGroupId", null);
  96805. return EffectLayer;
  96806. }());
  96807. BABYLON.EffectLayer = EffectLayer;
  96808. })(BABYLON || (BABYLON = {}));
  96809. //# sourceMappingURL=babylon.effectLayer.js.map
  96810. var BABYLON;
  96811. (function (BABYLON) {
  96812. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  96813. for (var index = 0; index < this.effectLayers.length; index++) {
  96814. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  96815. return this.effectLayers[index];
  96816. }
  96817. }
  96818. return null;
  96819. };
  96820. /**
  96821. * Special Glow Blur post process only blurring the alpha channel
  96822. * It enforces keeping the most luminous color in the color channel.
  96823. */
  96824. var GlowBlurPostProcess = /** @class */ (function (_super) {
  96825. __extends(GlowBlurPostProcess, _super);
  96826. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  96827. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  96828. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  96829. _this.direction = direction;
  96830. _this.kernel = kernel;
  96831. _this.onApplyObservable.add(function (effect) {
  96832. effect.setFloat2("screenSize", _this.width, _this.height);
  96833. effect.setVector2("direction", _this.direction);
  96834. effect.setFloat("blurWidth", _this.kernel);
  96835. });
  96836. return _this;
  96837. }
  96838. return GlowBlurPostProcess;
  96839. }(BABYLON.PostProcess));
  96840. /**
  96841. * The highlight layer Helps adding a glow effect around a mesh.
  96842. *
  96843. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  96844. * glowy meshes to your scene.
  96845. *
  96846. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  96847. */
  96848. var HighlightLayer = /** @class */ (function (_super) {
  96849. __extends(HighlightLayer, _super);
  96850. /**
  96851. * Instantiates a new highlight Layer and references it to the scene..
  96852. * @param name The name of the layer
  96853. * @param scene The scene to use the layer in
  96854. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  96855. */
  96856. function HighlightLayer(name, scene, options) {
  96857. var _this = _super.call(this, name, scene) || this;
  96858. _this.name = name;
  96859. /**
  96860. * Specifies whether or not the inner glow is ACTIVE in the layer.
  96861. */
  96862. _this.innerGlow = true;
  96863. /**
  96864. * Specifies whether or not the outer glow is ACTIVE in the layer.
  96865. */
  96866. _this.outerGlow = true;
  96867. /**
  96868. * An event triggered when the highlight layer is being blurred.
  96869. */
  96870. _this.onBeforeBlurObservable = new BABYLON.Observable();
  96871. /**
  96872. * An event triggered when the highlight layer has been blurred.
  96873. */
  96874. _this.onAfterBlurObservable = new BABYLON.Observable();
  96875. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  96876. _this._meshes = {};
  96877. _this._excludedMeshes = {};
  96878. _this.neutralColor = HighlightLayer.NeutralColor;
  96879. // Warn on stencil
  96880. if (!_this._engine.isStencilEnable) {
  96881. 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 }");
  96882. }
  96883. // Adapt options
  96884. _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);
  96885. // Initialize the layer
  96886. _this._init({
  96887. alphaBlendingMode: _this._options.alphaBlendingMode,
  96888. camera: _this._options.camera,
  96889. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  96890. mainTextureRatio: _this._options.mainTextureRatio,
  96891. renderingGroupId: _this._options.renderingGroupId
  96892. });
  96893. // Do not render as long as no meshes have been added
  96894. _this._shouldRender = false;
  96895. return _this;
  96896. }
  96897. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  96898. /**
  96899. * Gets the horizontal size of the blur.
  96900. */
  96901. get: function () {
  96902. return this._horizontalBlurPostprocess.kernel;
  96903. },
  96904. /**
  96905. * Specifies the horizontal size of the blur.
  96906. */
  96907. set: function (value) {
  96908. this._horizontalBlurPostprocess.kernel = value;
  96909. },
  96910. enumerable: true,
  96911. configurable: true
  96912. });
  96913. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  96914. /**
  96915. * Gets the vertical size of the blur.
  96916. */
  96917. get: function () {
  96918. return this._verticalBlurPostprocess.kernel;
  96919. },
  96920. /**
  96921. * Specifies the vertical size of the blur.
  96922. */
  96923. set: function (value) {
  96924. this._verticalBlurPostprocess.kernel = value;
  96925. },
  96926. enumerable: true,
  96927. configurable: true
  96928. });
  96929. /**
  96930. * Get the effect name of the layer.
  96931. * @return The effect name
  96932. */
  96933. HighlightLayer.prototype.getEffectName = function () {
  96934. return HighlightLayer.EffectName;
  96935. };
  96936. /**
  96937. * Create the merge effect. This is the shader use to blit the information back
  96938. * to the main canvas at the end of the scene rendering.
  96939. */
  96940. HighlightLayer.prototype._createMergeEffect = function () {
  96941. // Effect
  96942. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  96943. };
  96944. /**
  96945. * Creates the render target textures and post processes used in the highlight layer.
  96946. */
  96947. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  96948. var _this = this;
  96949. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  96950. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  96951. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  96952. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  96953. var textureType = 0;
  96954. if (this._engine.getCaps().textureHalfFloatRender) {
  96955. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96956. }
  96957. else {
  96958. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96959. }
  96960. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  96961. width: blurTextureWidth,
  96962. height: blurTextureHeight
  96963. }, this._scene, false, true, textureType);
  96964. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96965. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96966. this._blurTexture.anisotropicFilteringLevel = 16;
  96967. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  96968. this._blurTexture.renderParticles = false;
  96969. this._blurTexture.ignoreCameraViewport = true;
  96970. this._textures = [this._blurTexture];
  96971. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  96972. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96973. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  96974. effect.setTexture("textureSampler", _this._mainTexture);
  96975. });
  96976. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96977. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  96978. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  96979. });
  96980. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96981. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  96982. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  96983. });
  96984. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  96985. }
  96986. else {
  96987. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  96988. width: blurTextureWidth,
  96989. height: blurTextureHeight
  96990. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96991. this._horizontalBlurPostprocess.width = blurTextureWidth;
  96992. this._horizontalBlurPostprocess.height = blurTextureHeight;
  96993. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  96994. effect.setTexture("textureSampler", _this._mainTexture);
  96995. });
  96996. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  96997. width: blurTextureWidth,
  96998. height: blurTextureHeight
  96999. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97000. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97001. }
  97002. this._mainTexture.onAfterUnbindObservable.add(function () {
  97003. _this.onBeforeBlurObservable.notifyObservers(_this);
  97004. var internalTexture = _this._blurTexture.getInternalTexture();
  97005. if (internalTexture) {
  97006. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  97007. }
  97008. _this.onAfterBlurObservable.notifyObservers(_this);
  97009. });
  97010. // Prevent autoClear.
  97011. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97012. };
  97013. /**
  97014. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97015. */
  97016. HighlightLayer.prototype.needStencil = function () {
  97017. return true;
  97018. };
  97019. /**
  97020. * Checks for the readiness of the element composing the layer.
  97021. * @param subMesh the mesh to check for
  97022. * @param useInstances specify wether or not to use instances to render the mesh
  97023. * @param emissiveTexture the associated emissive texture used to generate the glow
  97024. * @return true if ready otherwise, false
  97025. */
  97026. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  97027. var material = subMesh.getMaterial();
  97028. var mesh = subMesh.getRenderingMesh();
  97029. if (!material || !mesh || !this._meshes) {
  97030. return false;
  97031. }
  97032. var emissiveTexture = null;
  97033. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97034. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97035. emissiveTexture = material.emissiveTexture;
  97036. }
  97037. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97038. };
  97039. /**
  97040. * Implementation specific of rendering the generating effect on the main canvas.
  97041. * @param effect The effect used to render through
  97042. */
  97043. HighlightLayer.prototype._internalRender = function (effect) {
  97044. // Texture
  97045. effect.setTexture("textureSampler", this._blurTexture);
  97046. // Cache
  97047. var engine = this._engine;
  97048. var previousStencilBuffer = engine.getStencilBuffer();
  97049. var previousStencilFunction = engine.getStencilFunction();
  97050. var previousStencilMask = engine.getStencilMask();
  97051. var previousStencilOperationPass = engine.getStencilOperationPass();
  97052. var previousStencilOperationFail = engine.getStencilOperationFail();
  97053. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  97054. var previousStencilReference = engine.getStencilFunctionReference();
  97055. // Stencil operations
  97056. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  97057. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  97058. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  97059. // Draw order
  97060. engine.setStencilMask(0x00);
  97061. engine.setStencilBuffer(true);
  97062. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  97063. // 2 passes inner outer
  97064. if (this.outerGlow) {
  97065. effect.setFloat("offset", 0);
  97066. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  97067. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97068. }
  97069. if (this.innerGlow) {
  97070. effect.setFloat("offset", 1);
  97071. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  97072. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97073. }
  97074. // Restore Cache
  97075. engine.setStencilFunction(previousStencilFunction);
  97076. engine.setStencilMask(previousStencilMask);
  97077. engine.setStencilBuffer(previousStencilBuffer);
  97078. engine.setStencilOperationPass(previousStencilOperationPass);
  97079. engine.setStencilOperationFail(previousStencilOperationFail);
  97080. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  97081. engine.setStencilFunctionReference(previousStencilReference);
  97082. };
  97083. /**
  97084. * Returns true if the layer contains information to display, otherwise false.
  97085. */
  97086. HighlightLayer.prototype.shouldRender = function () {
  97087. if (_super.prototype.shouldRender.call(this)) {
  97088. return this._meshes ? true : false;
  97089. }
  97090. return false;
  97091. };
  97092. /**
  97093. * Returns true if the mesh should render, otherwise false.
  97094. * @param mesh The mesh to render
  97095. * @returns true if it should render otherwise false
  97096. */
  97097. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  97098. // Excluded Mesh
  97099. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  97100. return false;
  97101. }
  97102. ;
  97103. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97104. return false;
  97105. }
  97106. return true;
  97107. };
  97108. /**
  97109. * Sets the required values for both the emissive texture and and the main color.
  97110. */
  97111. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97112. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97113. if (highlightLayerMesh) {
  97114. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  97115. }
  97116. else {
  97117. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97118. }
  97119. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97120. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97121. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  97122. }
  97123. else {
  97124. this._emissiveTextureAndColor.texture = null;
  97125. }
  97126. };
  97127. /**
  97128. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  97129. * @param mesh The mesh to exclude from the highlight layer
  97130. */
  97131. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  97132. if (!this._excludedMeshes) {
  97133. return;
  97134. }
  97135. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  97136. if (!meshExcluded) {
  97137. this._excludedMeshes[mesh.uniqueId] = {
  97138. mesh: mesh,
  97139. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  97140. mesh.getEngine().setStencilBuffer(false);
  97141. }),
  97142. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  97143. mesh.getEngine().setStencilBuffer(true);
  97144. }),
  97145. };
  97146. }
  97147. };
  97148. /**
  97149. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  97150. * @param mesh The mesh to highlight
  97151. */
  97152. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  97153. if (!this._excludedMeshes) {
  97154. return;
  97155. }
  97156. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  97157. if (meshExcluded) {
  97158. if (meshExcluded.beforeRender) {
  97159. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  97160. }
  97161. if (meshExcluded.afterRender) {
  97162. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  97163. }
  97164. }
  97165. this._excludedMeshes[mesh.uniqueId] = null;
  97166. };
  97167. /**
  97168. * Determine if a given mesh will be highlighted by the current HighlightLayer
  97169. * @param mesh mesh to test
  97170. * @returns true if the mesh will be highlighted by the current HighlightLayer
  97171. */
  97172. HighlightLayer.prototype.hasMesh = function (mesh) {
  97173. if (!this._meshes) {
  97174. return false;
  97175. }
  97176. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97177. return false;
  97178. }
  97179. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  97180. };
  97181. /**
  97182. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  97183. * @param mesh The mesh to highlight
  97184. * @param color The color of the highlight
  97185. * @param glowEmissiveOnly Extract the glow from the emissive texture
  97186. */
  97187. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  97188. var _this = this;
  97189. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  97190. if (!this._meshes) {
  97191. return;
  97192. }
  97193. var meshHighlight = this._meshes[mesh.uniqueId];
  97194. if (meshHighlight) {
  97195. meshHighlight.color = color;
  97196. }
  97197. else {
  97198. this._meshes[mesh.uniqueId] = {
  97199. mesh: mesh,
  97200. color: color,
  97201. // Lambda required for capture due to Observable this context
  97202. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  97203. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  97204. _this._defaultStencilReference(mesh);
  97205. }
  97206. else {
  97207. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  97208. }
  97209. }),
  97210. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  97211. glowEmissiveOnly: glowEmissiveOnly
  97212. };
  97213. mesh.onDisposeObservable.add(function () {
  97214. _this._disposeMesh(mesh);
  97215. });
  97216. }
  97217. this._shouldRender = true;
  97218. };
  97219. /**
  97220. * Remove a mesh from the highlight layer in order to make it stop glowing.
  97221. * @param mesh The mesh to highlight
  97222. */
  97223. HighlightLayer.prototype.removeMesh = function (mesh) {
  97224. if (!this._meshes) {
  97225. return;
  97226. }
  97227. var meshHighlight = this._meshes[mesh.uniqueId];
  97228. if (meshHighlight) {
  97229. if (meshHighlight.observerHighlight) {
  97230. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97231. }
  97232. if (meshHighlight.observerDefault) {
  97233. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97234. }
  97235. delete this._meshes[mesh.uniqueId];
  97236. }
  97237. this._shouldRender = false;
  97238. for (var meshHighlightToCheck in this._meshes) {
  97239. if (this._meshes[meshHighlightToCheck]) {
  97240. this._shouldRender = true;
  97241. break;
  97242. }
  97243. }
  97244. };
  97245. /**
  97246. * Force the stencil to the normal expected value for none glowing parts
  97247. */
  97248. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  97249. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  97250. };
  97251. /**
  97252. * Free any resources and references associated to a mesh.
  97253. * Internal use
  97254. * @param mesh The mesh to free.
  97255. */
  97256. HighlightLayer.prototype._disposeMesh = function (mesh) {
  97257. this.removeMesh(mesh);
  97258. this.removeExcludedMesh(mesh);
  97259. };
  97260. /**
  97261. * Dispose the highlight layer and free resources.
  97262. */
  97263. HighlightLayer.prototype.dispose = function () {
  97264. if (this._meshes) {
  97265. // Clean mesh references
  97266. for (var id in this._meshes) {
  97267. var meshHighlight = this._meshes[id];
  97268. if (meshHighlight && meshHighlight.mesh) {
  97269. if (meshHighlight.observerHighlight) {
  97270. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97271. }
  97272. if (meshHighlight.observerDefault) {
  97273. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97274. }
  97275. }
  97276. }
  97277. this._meshes = null;
  97278. }
  97279. if (this._excludedMeshes) {
  97280. for (var id in this._excludedMeshes) {
  97281. var meshHighlight = this._excludedMeshes[id];
  97282. if (meshHighlight) {
  97283. if (meshHighlight.beforeRender) {
  97284. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  97285. }
  97286. if (meshHighlight.afterRender) {
  97287. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  97288. }
  97289. }
  97290. }
  97291. this._excludedMeshes = null;
  97292. }
  97293. _super.prototype.dispose.call(this);
  97294. };
  97295. /**
  97296. * Gets the class name of the effect layer
  97297. * @returns the string with the class name of the effect layer
  97298. */
  97299. HighlightLayer.prototype.getClassName = function () {
  97300. return "HighlightLayer";
  97301. };
  97302. /**
  97303. * Serializes this Highlight layer
  97304. * @returns a serialized Highlight layer object
  97305. */
  97306. HighlightLayer.prototype.serialize = function () {
  97307. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97308. serializationObject.customType = "BABYLON.HighlightLayer";
  97309. // Highlighted meshes
  97310. serializationObject.meshes = [];
  97311. if (this._meshes) {
  97312. for (var m in this._meshes) {
  97313. var mesh = this._meshes[m];
  97314. if (mesh) {
  97315. serializationObject.meshes.push({
  97316. glowEmissiveOnly: mesh.glowEmissiveOnly,
  97317. color: mesh.color.asArray(),
  97318. meshId: mesh.mesh.id
  97319. });
  97320. }
  97321. }
  97322. }
  97323. // Excluded meshes
  97324. serializationObject.excludedMeshes = [];
  97325. if (this._excludedMeshes) {
  97326. for (var e in this._excludedMeshes) {
  97327. var excludedMesh = this._excludedMeshes[e];
  97328. if (excludedMesh) {
  97329. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  97330. }
  97331. }
  97332. }
  97333. return serializationObject;
  97334. };
  97335. /**
  97336. * Creates a Highlight layer from parsed Highlight layer data
  97337. * @param parsedHightlightLayer defines the Highlight layer data
  97338. * @param scene defines the current scene
  97339. * @param rootUrl defines the root URL containing the Highlight layer information
  97340. * @returns a parsed Highlight layer
  97341. */
  97342. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  97343. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  97344. var index;
  97345. // Excluded meshes
  97346. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  97347. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  97348. if (mesh) {
  97349. hl.addExcludedMesh(mesh);
  97350. }
  97351. }
  97352. // Included meshes
  97353. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  97354. var highlightedMesh = parsedHightlightLayer.meshes[index];
  97355. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  97356. if (mesh) {
  97357. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  97358. }
  97359. }
  97360. return hl;
  97361. };
  97362. /**
  97363. * Effect Name of the highlight layer.
  97364. */
  97365. HighlightLayer.EffectName = "HighlightLayer";
  97366. /**
  97367. * The neutral color used during the preparation of the glow effect.
  97368. * This is black by default as the blend operation is a blend operation.
  97369. */
  97370. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  97371. /**
  97372. * Stencil value used for glowing meshes.
  97373. */
  97374. HighlightLayer.GlowingMeshStencilReference = 0x02;
  97375. /**
  97376. * Stencil value used for the other meshes in the scene.
  97377. */
  97378. HighlightLayer.NormalMeshStencilReference = 0x01;
  97379. __decorate([
  97380. BABYLON.serialize()
  97381. ], HighlightLayer.prototype, "innerGlow", void 0);
  97382. __decorate([
  97383. BABYLON.serialize()
  97384. ], HighlightLayer.prototype, "outerGlow", void 0);
  97385. __decorate([
  97386. BABYLON.serialize()
  97387. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  97388. __decorate([
  97389. BABYLON.serialize()
  97390. ], HighlightLayer.prototype, "blurVerticalSize", null);
  97391. __decorate([
  97392. BABYLON.serialize("options")
  97393. ], HighlightLayer.prototype, "_options", void 0);
  97394. return HighlightLayer;
  97395. }(BABYLON.EffectLayer));
  97396. BABYLON.HighlightLayer = HighlightLayer;
  97397. })(BABYLON || (BABYLON = {}));
  97398. //# sourceMappingURL=babylon.highlightLayer.js.map
  97399. var BABYLON;
  97400. (function (BABYLON) {
  97401. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  97402. for (var index = 0; index < this.effectLayers.length; index++) {
  97403. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  97404. return this.effectLayers[index];
  97405. }
  97406. }
  97407. return null;
  97408. };
  97409. /**
  97410. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  97411. *
  97412. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97413. * glowy meshes to your scene.
  97414. *
  97415. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  97416. */
  97417. var GlowLayer = /** @class */ (function (_super) {
  97418. __extends(GlowLayer, _super);
  97419. /**
  97420. * Instantiates a new glow Layer and references it to the scene.
  97421. * @param name The name of the layer
  97422. * @param scene The scene to use the layer in
  97423. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  97424. */
  97425. function GlowLayer(name, scene, options) {
  97426. var _this = _super.call(this, name, scene) || this;
  97427. _this._intensity = 1.0;
  97428. _this._includedOnlyMeshes = [];
  97429. _this._excludedMeshes = [];
  97430. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  97431. // Adapt options
  97432. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  97433. // Initialize the layer
  97434. _this._init({
  97435. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  97436. camera: _this._options.camera,
  97437. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97438. mainTextureRatio: _this._options.mainTextureRatio,
  97439. renderingGroupId: _this._options.renderingGroupId
  97440. });
  97441. return _this;
  97442. }
  97443. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  97444. /**
  97445. * Gets the kernel size of the blur.
  97446. */
  97447. get: function () {
  97448. return this._horizontalBlurPostprocess1.kernel;
  97449. },
  97450. /**
  97451. * Sets the kernel size of the blur.
  97452. */
  97453. set: function (value) {
  97454. this._horizontalBlurPostprocess1.kernel = value;
  97455. this._verticalBlurPostprocess1.kernel = value;
  97456. this._horizontalBlurPostprocess2.kernel = value;
  97457. this._verticalBlurPostprocess2.kernel = value;
  97458. },
  97459. enumerable: true,
  97460. configurable: true
  97461. });
  97462. Object.defineProperty(GlowLayer.prototype, "intensity", {
  97463. /**
  97464. * Gets the glow intensity.
  97465. */
  97466. get: function () {
  97467. return this._intensity;
  97468. },
  97469. /**
  97470. * Sets the glow intensity.
  97471. */
  97472. set: function (value) {
  97473. this._intensity = value;
  97474. },
  97475. enumerable: true,
  97476. configurable: true
  97477. });
  97478. /**
  97479. * Get the effect name of the layer.
  97480. * @return The effect name
  97481. */
  97482. GlowLayer.prototype.getEffectName = function () {
  97483. return GlowLayer.EffectName;
  97484. };
  97485. /**
  97486. * Create the merge effect. This is the shader use to blit the information back
  97487. * to the main canvas at the end of the scene rendering.
  97488. */
  97489. GlowLayer.prototype._createMergeEffect = function () {
  97490. // Effect
  97491. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  97492. };
  97493. /**
  97494. * Creates the render target textures and post processes used in the glow layer.
  97495. */
  97496. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  97497. var _this = this;
  97498. var blurTextureWidth = this._mainTextureDesiredSize.width;
  97499. var blurTextureHeight = this._mainTextureDesiredSize.height;
  97500. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97501. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97502. var textureType = 0;
  97503. if (this._engine.getCaps().textureHalfFloatRender) {
  97504. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97505. }
  97506. else {
  97507. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97508. }
  97509. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  97510. width: blurTextureWidth,
  97511. height: blurTextureHeight
  97512. }, this._scene, false, true, textureType);
  97513. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97514. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97515. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97516. this._blurTexture1.renderParticles = false;
  97517. this._blurTexture1.ignoreCameraViewport = true;
  97518. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  97519. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  97520. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  97521. width: blurTextureWidth2,
  97522. height: blurTextureHeight2
  97523. }, this._scene, false, true, textureType);
  97524. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97525. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97526. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97527. this._blurTexture2.renderParticles = false;
  97528. this._blurTexture2.ignoreCameraViewport = true;
  97529. this._textures = [this._blurTexture1, this._blurTexture2];
  97530. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97531. width: blurTextureWidth,
  97532. height: blurTextureHeight
  97533. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97534. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  97535. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  97536. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  97537. effect.setTexture("textureSampler", _this._mainTexture);
  97538. });
  97539. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97540. width: blurTextureWidth,
  97541. height: blurTextureHeight
  97542. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97543. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97544. width: blurTextureWidth2,
  97545. height: blurTextureHeight2
  97546. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97547. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  97548. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  97549. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  97550. effect.setTexture("textureSampler", _this._blurTexture1);
  97551. });
  97552. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97553. width: blurTextureWidth2,
  97554. height: blurTextureHeight2
  97555. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97556. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97557. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  97558. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97559. this._mainTexture.samples = this._options.mainTextureSamples;
  97560. this._mainTexture.onAfterUnbindObservable.add(function () {
  97561. var internalTexture = _this._blurTexture1.getInternalTexture();
  97562. if (internalTexture) {
  97563. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  97564. internalTexture = _this._blurTexture2.getInternalTexture();
  97565. if (internalTexture) {
  97566. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  97567. }
  97568. }
  97569. });
  97570. // Prevent autoClear.
  97571. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97572. };
  97573. /**
  97574. * Checks for the readiness of the element composing the layer.
  97575. * @param subMesh the mesh to check for
  97576. * @param useInstances specify wether or not to use instances to render the mesh
  97577. * @param emissiveTexture the associated emissive texture used to generate the glow
  97578. * @return true if ready otherwise, false
  97579. */
  97580. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  97581. var material = subMesh.getMaterial();
  97582. var mesh = subMesh.getRenderingMesh();
  97583. if (!material || !mesh) {
  97584. return false;
  97585. }
  97586. var emissiveTexture = material.emissiveTexture;
  97587. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97588. };
  97589. /**
  97590. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97591. */
  97592. GlowLayer.prototype.needStencil = function () {
  97593. return false;
  97594. };
  97595. /**
  97596. * Implementation specific of rendering the generating effect on the main canvas.
  97597. * @param effect The effect used to render through
  97598. */
  97599. GlowLayer.prototype._internalRender = function (effect) {
  97600. // Texture
  97601. effect.setTexture("textureSampler", this._blurTexture1);
  97602. effect.setTexture("textureSampler2", this._blurTexture2);
  97603. effect.setFloat("offset", this._intensity);
  97604. // Cache
  97605. var engine = this._engine;
  97606. var previousStencilBuffer = engine.getStencilBuffer();
  97607. // Draw order
  97608. engine.setStencilBuffer(false);
  97609. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97610. // Draw order
  97611. engine.setStencilBuffer(previousStencilBuffer);
  97612. };
  97613. /**
  97614. * Sets the required values for both the emissive texture and and the main color.
  97615. */
  97616. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97617. var textureLevel = 1.0;
  97618. if (this.customEmissiveTextureSelector) {
  97619. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  97620. }
  97621. else {
  97622. if (material) {
  97623. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97624. if (this._emissiveTextureAndColor.texture) {
  97625. textureLevel = this._emissiveTextureAndColor.texture.level;
  97626. }
  97627. }
  97628. else {
  97629. this._emissiveTextureAndColor.texture = null;
  97630. }
  97631. }
  97632. if (this.customEmissiveColorSelector) {
  97633. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  97634. }
  97635. else {
  97636. if (material.emissiveColor) {
  97637. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  97638. }
  97639. else {
  97640. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97641. }
  97642. }
  97643. };
  97644. /**
  97645. * Returns true if the mesh should render, otherwise false.
  97646. * @param mesh The mesh to render
  97647. * @returns true if it should render otherwise false
  97648. */
  97649. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  97650. return this.hasMesh(mesh);
  97651. };
  97652. /**
  97653. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  97654. * @param mesh The mesh to exclude from the glow layer
  97655. */
  97656. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  97657. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  97658. this._excludedMeshes.push(mesh.uniqueId);
  97659. }
  97660. };
  97661. /**
  97662. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  97663. * @param mesh The mesh to remove
  97664. */
  97665. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  97666. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  97667. if (index !== -1) {
  97668. this._excludedMeshes.splice(index, 1);
  97669. }
  97670. };
  97671. /**
  97672. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  97673. * @param mesh The mesh to include in the glow layer
  97674. */
  97675. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  97676. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  97677. this._includedOnlyMeshes.push(mesh.uniqueId);
  97678. }
  97679. };
  97680. /**
  97681. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  97682. * @param mesh The mesh to remove
  97683. */
  97684. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  97685. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  97686. if (index !== -1) {
  97687. this._includedOnlyMeshes.splice(index, 1);
  97688. }
  97689. };
  97690. /**
  97691. * Determine if a given mesh will be used in the glow layer
  97692. * @param mesh The mesh to test
  97693. * @returns true if the mesh will be highlighted by the current glow layer
  97694. */
  97695. GlowLayer.prototype.hasMesh = function (mesh) {
  97696. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97697. return false;
  97698. }
  97699. // Included Mesh
  97700. if (this._includedOnlyMeshes.length) {
  97701. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  97702. }
  97703. ;
  97704. // Excluded Mesh
  97705. if (this._excludedMeshes.length) {
  97706. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  97707. }
  97708. ;
  97709. return true;
  97710. };
  97711. /**
  97712. * Free any resources and references associated to a mesh.
  97713. * Internal use
  97714. * @param mesh The mesh to free.
  97715. */
  97716. GlowLayer.prototype._disposeMesh = function (mesh) {
  97717. this.removeIncludedOnlyMesh(mesh);
  97718. this.removeExcludedMesh(mesh);
  97719. };
  97720. /**
  97721. * Gets the class name of the effect layer
  97722. * @returns the string with the class name of the effect layer
  97723. */
  97724. GlowLayer.prototype.getClassName = function () {
  97725. return "GlowLayer";
  97726. };
  97727. /**
  97728. * Serializes this glow layer
  97729. * @returns a serialized glow layer object
  97730. */
  97731. GlowLayer.prototype.serialize = function () {
  97732. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97733. serializationObject.customType = "BABYLON.GlowLayer";
  97734. var index;
  97735. // Included meshes
  97736. serializationObject.includedMeshes = [];
  97737. if (this._includedOnlyMeshes.length) {
  97738. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  97739. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  97740. if (mesh) {
  97741. serializationObject.includedMeshes.push(mesh.id);
  97742. }
  97743. }
  97744. }
  97745. // Excluded meshes
  97746. serializationObject.excludedMeshes = [];
  97747. if (this._excludedMeshes.length) {
  97748. for (index = 0; index < this._excludedMeshes.length; index++) {
  97749. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  97750. if (mesh) {
  97751. serializationObject.excludedMeshes.push(mesh.id);
  97752. }
  97753. }
  97754. }
  97755. return serializationObject;
  97756. };
  97757. /**
  97758. * Creates a Glow Layer from parsed glow layer data
  97759. * @param parsedGlowLayer defines glow layer data
  97760. * @param scene defines the current scene
  97761. * @param rootUrl defines the root URL containing the glow layer information
  97762. * @returns a parsed Glow Layer
  97763. */
  97764. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  97765. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  97766. var index;
  97767. // Excluded meshes
  97768. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  97769. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  97770. if (mesh) {
  97771. gl.addExcludedMesh(mesh);
  97772. }
  97773. }
  97774. // Included meshes
  97775. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  97776. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  97777. if (mesh) {
  97778. gl.addIncludedOnlyMesh(mesh);
  97779. }
  97780. }
  97781. return gl;
  97782. };
  97783. /**
  97784. * Effect Name of the layer.
  97785. */
  97786. GlowLayer.EffectName = "GlowLayer";
  97787. /**
  97788. * The default blur kernel size used for the glow.
  97789. */
  97790. GlowLayer.DefaultBlurKernelSize = 32;
  97791. /**
  97792. * The default texture size ratio used for the glow.
  97793. */
  97794. GlowLayer.DefaultTextureRatio = 0.5;
  97795. __decorate([
  97796. BABYLON.serialize()
  97797. ], GlowLayer.prototype, "blurKernelSize", null);
  97798. __decorate([
  97799. BABYLON.serialize()
  97800. ], GlowLayer.prototype, "intensity", null);
  97801. __decorate([
  97802. BABYLON.serialize("options")
  97803. ], GlowLayer.prototype, "_options", void 0);
  97804. return GlowLayer;
  97805. }(BABYLON.EffectLayer));
  97806. BABYLON.GlowLayer = GlowLayer;
  97807. })(BABYLON || (BABYLON = {}));
  97808. //# sourceMappingURL=babylon.glowLayer.js.map
  97809. var BABYLON;
  97810. (function (BABYLON) {
  97811. /**
  97812. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  97813. */
  97814. var AssetTaskState;
  97815. (function (AssetTaskState) {
  97816. /**
  97817. * Initialization
  97818. */
  97819. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  97820. /**
  97821. * Running
  97822. */
  97823. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  97824. /**
  97825. * Done
  97826. */
  97827. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  97828. /**
  97829. * Error
  97830. */
  97831. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  97832. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  97833. /**
  97834. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  97835. */
  97836. var AbstractAssetTask = /** @class */ (function () {
  97837. /**
  97838. * Creates a new {BABYLON.AssetsManager}
  97839. * @param name defines the name of the task
  97840. */
  97841. function AbstractAssetTask(
  97842. /**
  97843. * Task name
  97844. */ name) {
  97845. this.name = name;
  97846. this._isCompleted = false;
  97847. this._taskState = AssetTaskState.INIT;
  97848. }
  97849. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  97850. /**
  97851. * Get if the task is completed
  97852. */
  97853. get: function () {
  97854. return this._isCompleted;
  97855. },
  97856. enumerable: true,
  97857. configurable: true
  97858. });
  97859. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  97860. /**
  97861. * Gets the current state of the task
  97862. */
  97863. get: function () {
  97864. return this._taskState;
  97865. },
  97866. enumerable: true,
  97867. configurable: true
  97868. });
  97869. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  97870. /**
  97871. * Gets the current error object (if task is in error)
  97872. */
  97873. get: function () {
  97874. return this._errorObject;
  97875. },
  97876. enumerable: true,
  97877. configurable: true
  97878. });
  97879. /**
  97880. * Internal only
  97881. * @hidden
  97882. */
  97883. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  97884. if (this._errorObject) {
  97885. return;
  97886. }
  97887. this._errorObject = {
  97888. message: message,
  97889. exception: exception
  97890. };
  97891. };
  97892. /**
  97893. * Execute the current task
  97894. * @param scene defines the scene where you want your assets to be loaded
  97895. * @param onSuccess is a callback called when the task is successfully executed
  97896. * @param onError is a callback called if an error occurs
  97897. */
  97898. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  97899. var _this = this;
  97900. this._taskState = AssetTaskState.RUNNING;
  97901. this.runTask(scene, function () {
  97902. _this.onDoneCallback(onSuccess, onError);
  97903. }, function (msg, exception) {
  97904. _this.onErrorCallback(onError, msg, exception);
  97905. });
  97906. };
  97907. /**
  97908. * Execute the current task
  97909. * @param scene defines the scene where you want your assets to be loaded
  97910. * @param onSuccess is a callback called when the task is successfully executed
  97911. * @param onError is a callback called if an error occurs
  97912. */
  97913. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97914. throw new Error("runTask is not implemented");
  97915. };
  97916. /**
  97917. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  97918. * This can be used with failed tasks that have the reason for failure fixed.
  97919. */
  97920. AbstractAssetTask.prototype.reset = function () {
  97921. this._taskState = AssetTaskState.INIT;
  97922. };
  97923. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  97924. this._taskState = AssetTaskState.ERROR;
  97925. this._errorObject = {
  97926. message: message,
  97927. exception: exception
  97928. };
  97929. if (this.onError) {
  97930. this.onError(this, message, exception);
  97931. }
  97932. onError();
  97933. };
  97934. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  97935. try {
  97936. this._taskState = AssetTaskState.DONE;
  97937. this._isCompleted = true;
  97938. if (this.onSuccess) {
  97939. this.onSuccess(this);
  97940. }
  97941. onSuccess();
  97942. }
  97943. catch (e) {
  97944. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  97945. }
  97946. };
  97947. return AbstractAssetTask;
  97948. }());
  97949. BABYLON.AbstractAssetTask = AbstractAssetTask;
  97950. /**
  97951. * Class used to share progress information about assets loading
  97952. */
  97953. var AssetsProgressEvent = /** @class */ (function () {
  97954. /**
  97955. * Creates a {BABYLON.AssetsProgressEvent}
  97956. * @param remainingCount defines the number of remaining tasks to process
  97957. * @param totalCount defines the total number of tasks
  97958. * @param task defines the task that was just processed
  97959. */
  97960. function AssetsProgressEvent(remainingCount, totalCount, task) {
  97961. this.remainingCount = remainingCount;
  97962. this.totalCount = totalCount;
  97963. this.task = task;
  97964. }
  97965. return AssetsProgressEvent;
  97966. }());
  97967. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  97968. /**
  97969. * Define a task used by {BABYLON.AssetsManager} to load meshes
  97970. */
  97971. var MeshAssetTask = /** @class */ (function (_super) {
  97972. __extends(MeshAssetTask, _super);
  97973. /**
  97974. * Creates a new {BABYLON.MeshAssetTask}
  97975. * @param name defines the name of the task
  97976. * @param meshesNames defines the list of mesh's names you want to load
  97977. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  97978. * @param sceneFilename defines the filename of the scene to load from
  97979. */
  97980. function MeshAssetTask(
  97981. /**
  97982. * Defines the name of the task
  97983. */
  97984. name,
  97985. /**
  97986. * Defines the list of mesh's names you want to load
  97987. */
  97988. meshesNames,
  97989. /**
  97990. * Defines the root url to use as a base to load your meshes and associated resources
  97991. */
  97992. rootUrl,
  97993. /**
  97994. * Defines the filename of the scene to load from
  97995. */
  97996. sceneFilename) {
  97997. var _this = _super.call(this, name) || this;
  97998. _this.name = name;
  97999. _this.meshesNames = meshesNames;
  98000. _this.rootUrl = rootUrl;
  98001. _this.sceneFilename = sceneFilename;
  98002. return _this;
  98003. }
  98004. /**
  98005. * Execute the current task
  98006. * @param scene defines the scene where you want your assets to be loaded
  98007. * @param onSuccess is a callback called when the task is successfully executed
  98008. * @param onError is a callback called if an error occurs
  98009. */
  98010. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98011. var _this = this;
  98012. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  98013. _this.loadedMeshes = meshes;
  98014. _this.loadedParticleSystems = particleSystems;
  98015. _this.loadedSkeletons = skeletons;
  98016. onSuccess();
  98017. }, null, function (scene, message, exception) {
  98018. onError(message, exception);
  98019. });
  98020. };
  98021. return MeshAssetTask;
  98022. }(AbstractAssetTask));
  98023. BABYLON.MeshAssetTask = MeshAssetTask;
  98024. /**
  98025. * Define a task used by {BABYLON.AssetsManager} to load text content
  98026. */
  98027. var TextFileAssetTask = /** @class */ (function (_super) {
  98028. __extends(TextFileAssetTask, _super);
  98029. /**
  98030. * Creates a new TextFileAssetTask object
  98031. * @param name defines the name of the task
  98032. * @param url defines the location of the file to load
  98033. */
  98034. function TextFileAssetTask(
  98035. /**
  98036. * Defines the name of the task
  98037. */
  98038. name,
  98039. /**
  98040. * Defines the location of the file to load
  98041. */
  98042. url) {
  98043. var _this = _super.call(this, name) || this;
  98044. _this.name = name;
  98045. _this.url = url;
  98046. return _this;
  98047. }
  98048. /**
  98049. * Execute the current task
  98050. * @param scene defines the scene where you want your assets to be loaded
  98051. * @param onSuccess is a callback called when the task is successfully executed
  98052. * @param onError is a callback called if an error occurs
  98053. */
  98054. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98055. var _this = this;
  98056. scene._loadFile(this.url, function (data) {
  98057. _this.text = data;
  98058. onSuccess();
  98059. }, undefined, false, false, function (request, exception) {
  98060. if (request) {
  98061. onError(request.status + " " + request.statusText, exception);
  98062. }
  98063. });
  98064. };
  98065. return TextFileAssetTask;
  98066. }(AbstractAssetTask));
  98067. BABYLON.TextFileAssetTask = TextFileAssetTask;
  98068. /**
  98069. * Define a task used by {BABYLON.AssetsManager} to load binary data
  98070. */
  98071. var BinaryFileAssetTask = /** @class */ (function (_super) {
  98072. __extends(BinaryFileAssetTask, _super);
  98073. /**
  98074. * Creates a new BinaryFileAssetTask object
  98075. * @param name defines the name of the new task
  98076. * @param url defines the location of the file to load
  98077. */
  98078. function BinaryFileAssetTask(
  98079. /**
  98080. * Defines the name of the task
  98081. */
  98082. name,
  98083. /**
  98084. * Defines the location of the file to load
  98085. */
  98086. url) {
  98087. var _this = _super.call(this, name) || this;
  98088. _this.name = name;
  98089. _this.url = url;
  98090. return _this;
  98091. }
  98092. /**
  98093. * Execute the current task
  98094. * @param scene defines the scene where you want your assets to be loaded
  98095. * @param onSuccess is a callback called when the task is successfully executed
  98096. * @param onError is a callback called if an error occurs
  98097. */
  98098. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98099. var _this = this;
  98100. scene._loadFile(this.url, function (data) {
  98101. _this.data = data;
  98102. onSuccess();
  98103. }, undefined, true, true, function (request, exception) {
  98104. if (request) {
  98105. onError(request.status + " " + request.statusText, exception);
  98106. }
  98107. });
  98108. };
  98109. return BinaryFileAssetTask;
  98110. }(AbstractAssetTask));
  98111. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  98112. /**
  98113. * Define a task used by {BABYLON.AssetsManager} to load images
  98114. */
  98115. var ImageAssetTask = /** @class */ (function (_super) {
  98116. __extends(ImageAssetTask, _super);
  98117. /**
  98118. * Creates a new ImageAssetTask
  98119. * @param name defines the name of the task
  98120. * @param url defines the location of the image to load
  98121. */
  98122. function ImageAssetTask(
  98123. /**
  98124. * Defines the name of the task
  98125. */
  98126. name,
  98127. /**
  98128. * Defines the location of the image to load
  98129. */
  98130. url) {
  98131. var _this = _super.call(this, name) || this;
  98132. _this.name = name;
  98133. _this.url = url;
  98134. return _this;
  98135. }
  98136. /**
  98137. * Execute the current task
  98138. * @param scene defines the scene where you want your assets to be loaded
  98139. * @param onSuccess is a callback called when the task is successfully executed
  98140. * @param onError is a callback called if an error occurs
  98141. */
  98142. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98143. var _this = this;
  98144. var img = new Image();
  98145. BABYLON.Tools.SetCorsBehavior(this.url, img);
  98146. img.onload = function () {
  98147. _this.image = img;
  98148. onSuccess();
  98149. };
  98150. img.onerror = function (err) {
  98151. onError("Error loading image", err);
  98152. };
  98153. img.src = this.url;
  98154. };
  98155. return ImageAssetTask;
  98156. }(AbstractAssetTask));
  98157. BABYLON.ImageAssetTask = ImageAssetTask;
  98158. /**
  98159. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  98160. */
  98161. var TextureAssetTask = /** @class */ (function (_super) {
  98162. __extends(TextureAssetTask, _super);
  98163. /**
  98164. * Creates a new TextureAssetTask object
  98165. * @param name defines the name of the task
  98166. * @param url defines the location of the file to load
  98167. * @param noMipmap defines if mipmap should not be generated (default is false)
  98168. * @param invertY defines if texture must be inverted on Y axis (default is false)
  98169. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  98170. */
  98171. function TextureAssetTask(
  98172. /**
  98173. * Defines the name of the task
  98174. */
  98175. name,
  98176. /**
  98177. * Defines the location of the file to load
  98178. */
  98179. url,
  98180. /**
  98181. * Defines if mipmap should not be generated (default is false)
  98182. */
  98183. noMipmap,
  98184. /**
  98185. * Defines if texture must be inverted on Y axis (default is false)
  98186. */
  98187. invertY,
  98188. /**
  98189. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  98190. */
  98191. samplingMode) {
  98192. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98193. var _this = _super.call(this, name) || this;
  98194. _this.name = name;
  98195. _this.url = url;
  98196. _this.noMipmap = noMipmap;
  98197. _this.invertY = invertY;
  98198. _this.samplingMode = samplingMode;
  98199. return _this;
  98200. }
  98201. /**
  98202. * Execute the current task
  98203. * @param scene defines the scene where you want your assets to be loaded
  98204. * @param onSuccess is a callback called when the task is successfully executed
  98205. * @param onError is a callback called if an error occurs
  98206. */
  98207. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98208. var onload = function () {
  98209. onSuccess();
  98210. };
  98211. var onerror = function (message, exception) {
  98212. onError(message, exception);
  98213. };
  98214. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  98215. };
  98216. return TextureAssetTask;
  98217. }(AbstractAssetTask));
  98218. BABYLON.TextureAssetTask = TextureAssetTask;
  98219. /**
  98220. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  98221. */
  98222. var CubeTextureAssetTask = /** @class */ (function (_super) {
  98223. __extends(CubeTextureAssetTask, _super);
  98224. /**
  98225. * Creates a new CubeTextureAssetTask
  98226. * @param name defines the name of the task
  98227. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98228. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98229. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98230. * @param files defines the explicit list of files (undefined by default)
  98231. */
  98232. function CubeTextureAssetTask(
  98233. /**
  98234. * Defines the name of the task
  98235. */
  98236. name,
  98237. /**
  98238. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98239. */
  98240. url,
  98241. /**
  98242. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98243. */
  98244. extensions,
  98245. /**
  98246. * Defines if mipmaps should not be generated (default is false)
  98247. */
  98248. noMipmap,
  98249. /**
  98250. * Defines the explicit list of files (undefined by default)
  98251. */
  98252. files) {
  98253. var _this = _super.call(this, name) || this;
  98254. _this.name = name;
  98255. _this.url = url;
  98256. _this.extensions = extensions;
  98257. _this.noMipmap = noMipmap;
  98258. _this.files = files;
  98259. return _this;
  98260. }
  98261. /**
  98262. * Execute the current task
  98263. * @param scene defines the scene where you want your assets to be loaded
  98264. * @param onSuccess is a callback called when the task is successfully executed
  98265. * @param onError is a callback called if an error occurs
  98266. */
  98267. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98268. var onload = function () {
  98269. onSuccess();
  98270. };
  98271. var onerror = function (message, exception) {
  98272. onError(message, exception);
  98273. };
  98274. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  98275. };
  98276. return CubeTextureAssetTask;
  98277. }(AbstractAssetTask));
  98278. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  98279. /**
  98280. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  98281. */
  98282. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  98283. __extends(HDRCubeTextureAssetTask, _super);
  98284. /**
  98285. * Creates a new HDRCubeTextureAssetTask object
  98286. * @param name defines the name of the task
  98287. * @param url defines the location of the file to load
  98288. * @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.
  98289. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98290. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98291. * @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)
  98292. * @param reserved Internal use only
  98293. */
  98294. function HDRCubeTextureAssetTask(
  98295. /**
  98296. * Defines the name of the task
  98297. */
  98298. name,
  98299. /**
  98300. * Defines the location of the file to load
  98301. */
  98302. url,
  98303. /**
  98304. * Defines the desired size (the more it increases the longer the generation will be)
  98305. */
  98306. size,
  98307. /**
  98308. * Defines if mipmaps should not be generated (default is false)
  98309. */
  98310. noMipmap,
  98311. /**
  98312. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98313. */
  98314. generateHarmonics,
  98315. /**
  98316. * 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)
  98317. */
  98318. gammaSpace,
  98319. /**
  98320. * Internal Use Only
  98321. */
  98322. reserved) {
  98323. if (noMipmap === void 0) { noMipmap = false; }
  98324. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98325. if (gammaSpace === void 0) { gammaSpace = false; }
  98326. if (reserved === void 0) { reserved = false; }
  98327. var _this = _super.call(this, name) || this;
  98328. _this.name = name;
  98329. _this.url = url;
  98330. _this.size = size;
  98331. _this.noMipmap = noMipmap;
  98332. _this.generateHarmonics = generateHarmonics;
  98333. _this.gammaSpace = gammaSpace;
  98334. _this.reserved = reserved;
  98335. return _this;
  98336. }
  98337. /**
  98338. * Execute the current task
  98339. * @param scene defines the scene where you want your assets to be loaded
  98340. * @param onSuccess is a callback called when the task is successfully executed
  98341. * @param onError is a callback called if an error occurs
  98342. */
  98343. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98344. var onload = function () {
  98345. onSuccess();
  98346. };
  98347. var onerror = function (message, exception) {
  98348. onError(message, exception);
  98349. };
  98350. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  98351. };
  98352. return HDRCubeTextureAssetTask;
  98353. }(AbstractAssetTask));
  98354. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  98355. /**
  98356. * This class can be used to easily import assets into a scene
  98357. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  98358. */
  98359. var AssetsManager = /** @class */ (function () {
  98360. /**
  98361. * Creates a new AssetsManager
  98362. * @param scene defines the scene to work on
  98363. */
  98364. function AssetsManager(scene) {
  98365. this._isLoading = false;
  98366. this._tasks = new Array();
  98367. this._waitingTasksCount = 0;
  98368. this._totalTasksCount = 0;
  98369. /**
  98370. * Observable called when all tasks are processed
  98371. */
  98372. this.onTaskSuccessObservable = new BABYLON.Observable();
  98373. /**
  98374. * Observable called when a task had an error
  98375. */
  98376. this.onTaskErrorObservable = new BABYLON.Observable();
  98377. /**
  98378. * Observable called when a task is successful
  98379. */
  98380. this.onTasksDoneObservable = new BABYLON.Observable();
  98381. /**
  98382. * Observable called when a task is done (whatever the result is)
  98383. */
  98384. this.onProgressObservable = new BABYLON.Observable();
  98385. /**
  98386. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  98387. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  98388. */
  98389. this.useDefaultLoadingScreen = true;
  98390. this._scene = scene;
  98391. }
  98392. /**
  98393. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  98394. * @param taskName defines the name of the new task
  98395. * @param meshesNames defines the name of meshes to load
  98396. * @param rootUrl defines the root url to use to locate files
  98397. * @param sceneFilename defines the filename of the scene file
  98398. * @returns a new {BABYLON.MeshAssetTask} object
  98399. */
  98400. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  98401. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  98402. this._tasks.push(task);
  98403. return task;
  98404. };
  98405. /**
  98406. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  98407. * @param taskName defines the name of the new task
  98408. * @param url defines the url of the file to load
  98409. * @returns a new {BABYLON.TextFileAssetTask} object
  98410. */
  98411. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  98412. var task = new TextFileAssetTask(taskName, url);
  98413. this._tasks.push(task);
  98414. return task;
  98415. };
  98416. /**
  98417. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  98418. * @param taskName defines the name of the new task
  98419. * @param url defines the url of the file to load
  98420. * @returns a new {BABYLON.BinaryFileAssetTask} object
  98421. */
  98422. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  98423. var task = new BinaryFileAssetTask(taskName, url);
  98424. this._tasks.push(task);
  98425. return task;
  98426. };
  98427. /**
  98428. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  98429. * @param taskName defines the name of the new task
  98430. * @param url defines the url of the file to load
  98431. * @returns a new {BABYLON.ImageAssetTask} object
  98432. */
  98433. AssetsManager.prototype.addImageTask = function (taskName, url) {
  98434. var task = new ImageAssetTask(taskName, url);
  98435. this._tasks.push(task);
  98436. return task;
  98437. };
  98438. /**
  98439. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  98440. * @param taskName defines the name of the new task
  98441. * @param url defines the url of the file to load
  98442. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98443. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  98444. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  98445. * @returns a new {BABYLON.TextureAssetTask} object
  98446. */
  98447. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  98448. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98449. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  98450. this._tasks.push(task);
  98451. return task;
  98452. };
  98453. /**
  98454. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  98455. * @param taskName defines the name of the new task
  98456. * @param url defines the url of the file to load
  98457. * @param extensions defines the extension to use to load the cube map (can be null)
  98458. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98459. * @param files defines the list of files to load (can be null)
  98460. * @returns a new {BABYLON.CubeTextureAssetTask} object
  98461. */
  98462. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  98463. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  98464. this._tasks.push(task);
  98465. return task;
  98466. };
  98467. /**
  98468. *
  98469. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  98470. * @param taskName defines the name of the new task
  98471. * @param url defines the url of the file to load
  98472. * @param size defines the size you want for the cubemap (can be null)
  98473. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98474. * @param generateHarmonics defines if you want to automatically generate (true by default)
  98475. * @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)
  98476. * @param reserved Internal use only
  98477. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  98478. */
  98479. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  98480. if (noMipmap === void 0) { noMipmap = false; }
  98481. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98482. if (gammaSpace === void 0) { gammaSpace = false; }
  98483. if (reserved === void 0) { reserved = false; }
  98484. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  98485. this._tasks.push(task);
  98486. return task;
  98487. };
  98488. /**
  98489. * Remove a task from the assets manager.
  98490. * @param task the task to remove
  98491. */
  98492. AssetsManager.prototype.removeTask = function (task) {
  98493. var index = this._tasks.indexOf(task);
  98494. if (index > -1) {
  98495. this._tasks.splice(index, 1);
  98496. }
  98497. };
  98498. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  98499. this._waitingTasksCount--;
  98500. try {
  98501. if (this.onProgress) {
  98502. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  98503. }
  98504. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  98505. }
  98506. catch (e) {
  98507. BABYLON.Tools.Error("Error running progress callbacks.");
  98508. console.log(e);
  98509. }
  98510. if (this._waitingTasksCount === 0) {
  98511. try {
  98512. if (this.onFinish) {
  98513. this.onFinish(this._tasks);
  98514. }
  98515. // Let's remove successfull tasks
  98516. var currentTasks = this._tasks.slice();
  98517. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  98518. var task = currentTasks_1[_i];
  98519. if (task.taskState === AssetTaskState.DONE) {
  98520. var index = this._tasks.indexOf(task);
  98521. if (index > -1) {
  98522. this._tasks.splice(index, 1);
  98523. }
  98524. }
  98525. }
  98526. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98527. }
  98528. catch (e) {
  98529. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  98530. console.log(e);
  98531. }
  98532. this._isLoading = false;
  98533. this._scene.getEngine().hideLoadingUI();
  98534. }
  98535. };
  98536. AssetsManager.prototype._runTask = function (task) {
  98537. var _this = this;
  98538. var done = function () {
  98539. try {
  98540. if (_this.onTaskSuccess) {
  98541. _this.onTaskSuccess(task);
  98542. }
  98543. _this.onTaskSuccessObservable.notifyObservers(task);
  98544. _this._decreaseWaitingTasksCount(task);
  98545. }
  98546. catch (e) {
  98547. error("Error executing task success callbacks", e);
  98548. }
  98549. };
  98550. var error = function (message, exception) {
  98551. task._setErrorObject(message, exception);
  98552. if (_this.onTaskError) {
  98553. _this.onTaskError(task);
  98554. }
  98555. _this.onTaskErrorObservable.notifyObservers(task);
  98556. _this._decreaseWaitingTasksCount(task);
  98557. };
  98558. task.run(this._scene, done, error);
  98559. };
  98560. /**
  98561. * Reset the {BABYLON.AssetsManager} and remove all tasks
  98562. * @return the current instance of the {BABYLON.AssetsManager}
  98563. */
  98564. AssetsManager.prototype.reset = function () {
  98565. this._isLoading = false;
  98566. this._tasks = new Array();
  98567. return this;
  98568. };
  98569. /**
  98570. * Start the loading process
  98571. * @return the current instance of the {BABYLON.AssetsManager}
  98572. */
  98573. AssetsManager.prototype.load = function () {
  98574. if (this._isLoading) {
  98575. return this;
  98576. }
  98577. this._isLoading = true;
  98578. this._waitingTasksCount = this._tasks.length;
  98579. this._totalTasksCount = this._tasks.length;
  98580. if (this._waitingTasksCount === 0) {
  98581. this._isLoading = false;
  98582. if (this.onFinish) {
  98583. this.onFinish(this._tasks);
  98584. }
  98585. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98586. return this;
  98587. }
  98588. if (this.useDefaultLoadingScreen) {
  98589. this._scene.getEngine().displayLoadingUI();
  98590. }
  98591. for (var index = 0; index < this._tasks.length; index++) {
  98592. var task = this._tasks[index];
  98593. if (task.taskState === AssetTaskState.INIT) {
  98594. this._runTask(task);
  98595. }
  98596. }
  98597. return this;
  98598. };
  98599. return AssetsManager;
  98600. }());
  98601. BABYLON.AssetsManager = AssetsManager;
  98602. })(BABYLON || (BABYLON = {}));
  98603. //# sourceMappingURL=babylon.assetsManager.js.map
  98604. var BABYLON;
  98605. (function (BABYLON) {
  98606. var serializedGeometries = [];
  98607. var serializeGeometry = function (geometry, serializationGeometries) {
  98608. if (serializedGeometries[geometry.id]) {
  98609. return;
  98610. }
  98611. if (geometry.doNotSerialize) {
  98612. return;
  98613. }
  98614. if (geometry instanceof BABYLON.BoxGeometry) {
  98615. serializationGeometries.boxes.push(geometry.serialize());
  98616. }
  98617. else if (geometry instanceof BABYLON.SphereGeometry) {
  98618. serializationGeometries.spheres.push(geometry.serialize());
  98619. }
  98620. else if (geometry instanceof BABYLON.CylinderGeometry) {
  98621. serializationGeometries.cylinders.push(geometry.serialize());
  98622. }
  98623. else if (geometry instanceof BABYLON.TorusGeometry) {
  98624. serializationGeometries.toruses.push(geometry.serialize());
  98625. }
  98626. else if (geometry instanceof BABYLON.GroundGeometry) {
  98627. serializationGeometries.grounds.push(geometry.serialize());
  98628. }
  98629. else if (geometry instanceof BABYLON.Plane) {
  98630. serializationGeometries.planes.push(geometry.serialize());
  98631. }
  98632. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  98633. serializationGeometries.torusKnots.push(geometry.serialize());
  98634. }
  98635. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  98636. throw new Error("Unknown primitive type");
  98637. }
  98638. else {
  98639. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  98640. }
  98641. serializedGeometries[geometry.id] = true;
  98642. };
  98643. var serializeMesh = function (mesh, serializationScene) {
  98644. var serializationObject = {};
  98645. // Geometry
  98646. var geometry = mesh._geometry;
  98647. if (geometry) {
  98648. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  98649. // 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
  98650. serializeGeometry(geometry, serializationScene.geometries);
  98651. }
  98652. }
  98653. // Custom
  98654. if (mesh.serialize) {
  98655. mesh.serialize(serializationObject);
  98656. }
  98657. return serializationObject;
  98658. };
  98659. var finalizeSingleMesh = function (mesh, serializationObject) {
  98660. //only works if the mesh is already loaded
  98661. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98662. //serialize material
  98663. if (mesh.material) {
  98664. if (mesh.material instanceof BABYLON.MultiMaterial) {
  98665. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  98666. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98667. serializationObject.multiMaterials.push(mesh.material.serialize());
  98668. }
  98669. }
  98670. else {
  98671. serializationObject.materials = serializationObject.materials || [];
  98672. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98673. serializationObject.materials.push(mesh.material.serialize());
  98674. }
  98675. }
  98676. }
  98677. //serialize geometry
  98678. var geometry = mesh._geometry;
  98679. if (geometry) {
  98680. if (!serializationObject.geometries) {
  98681. serializationObject.geometries = {};
  98682. serializationObject.geometries.boxes = [];
  98683. serializationObject.geometries.spheres = [];
  98684. serializationObject.geometries.cylinders = [];
  98685. serializationObject.geometries.toruses = [];
  98686. serializationObject.geometries.grounds = [];
  98687. serializationObject.geometries.planes = [];
  98688. serializationObject.geometries.torusKnots = [];
  98689. serializationObject.geometries.vertexData = [];
  98690. }
  98691. serializeGeometry(geometry, serializationObject.geometries);
  98692. }
  98693. // Skeletons
  98694. if (mesh.skeleton) {
  98695. serializationObject.skeletons = serializationObject.skeletons || [];
  98696. serializationObject.skeletons.push(mesh.skeleton.serialize());
  98697. }
  98698. //serialize the actual mesh
  98699. serializationObject.meshes = serializationObject.meshes || [];
  98700. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98701. }
  98702. };
  98703. var SceneSerializer = /** @class */ (function () {
  98704. function SceneSerializer() {
  98705. }
  98706. SceneSerializer.ClearCache = function () {
  98707. serializedGeometries = [];
  98708. };
  98709. SceneSerializer.Serialize = function (scene) {
  98710. var serializationObject = {};
  98711. SceneSerializer.ClearCache();
  98712. // Scene
  98713. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  98714. serializationObject.autoClear = scene.autoClear;
  98715. serializationObject.clearColor = scene.clearColor.asArray();
  98716. serializationObject.ambientColor = scene.ambientColor.asArray();
  98717. serializationObject.gravity = scene.gravity.asArray();
  98718. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  98719. serializationObject.workerCollisions = scene.workerCollisions;
  98720. // Fog
  98721. if (scene.fogMode && scene.fogMode !== 0) {
  98722. serializationObject.fogMode = scene.fogMode;
  98723. serializationObject.fogColor = scene.fogColor.asArray();
  98724. serializationObject.fogStart = scene.fogStart;
  98725. serializationObject.fogEnd = scene.fogEnd;
  98726. serializationObject.fogDensity = scene.fogDensity;
  98727. }
  98728. //Physics
  98729. if (scene.isPhysicsEnabled()) {
  98730. var physicEngine = scene.getPhysicsEngine();
  98731. if (physicEngine) {
  98732. serializationObject.physicsEnabled = true;
  98733. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  98734. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  98735. }
  98736. }
  98737. // Metadata
  98738. if (scene.metadata) {
  98739. serializationObject.metadata = scene.metadata;
  98740. }
  98741. // Morph targets
  98742. serializationObject.morphTargetManagers = [];
  98743. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  98744. var abstractMesh = _a[_i];
  98745. var manager = abstractMesh.morphTargetManager;
  98746. if (manager) {
  98747. serializationObject.morphTargetManagers.push(manager.serialize());
  98748. }
  98749. }
  98750. // Lights
  98751. serializationObject.lights = [];
  98752. var index;
  98753. var light;
  98754. for (index = 0; index < scene.lights.length; index++) {
  98755. light = scene.lights[index];
  98756. if (!light.doNotSerialize) {
  98757. serializationObject.lights.push(light.serialize());
  98758. }
  98759. }
  98760. // Cameras
  98761. serializationObject.cameras = [];
  98762. for (index = 0; index < scene.cameras.length; index++) {
  98763. var camera = scene.cameras[index];
  98764. if (!camera.doNotSerialize) {
  98765. serializationObject.cameras.push(camera.serialize());
  98766. }
  98767. }
  98768. if (scene.activeCamera) {
  98769. serializationObject.activeCameraID = scene.activeCamera.id;
  98770. }
  98771. // Animations
  98772. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  98773. // Materials
  98774. serializationObject.materials = [];
  98775. serializationObject.multiMaterials = [];
  98776. var material;
  98777. for (index = 0; index < scene.materials.length; index++) {
  98778. material = scene.materials[index];
  98779. if (!material.doNotSerialize) {
  98780. serializationObject.materials.push(material.serialize());
  98781. }
  98782. }
  98783. // MultiMaterials
  98784. serializationObject.multiMaterials = [];
  98785. for (index = 0; index < scene.multiMaterials.length; index++) {
  98786. var multiMaterial = scene.multiMaterials[index];
  98787. serializationObject.multiMaterials.push(multiMaterial.serialize());
  98788. }
  98789. // Environment texture
  98790. if (scene.environmentTexture) {
  98791. serializationObject.environmentTexture = scene.environmentTexture.name;
  98792. }
  98793. // Skeletons
  98794. serializationObject.skeletons = [];
  98795. for (index = 0; index < scene.skeletons.length; index++) {
  98796. var skeleton = scene.skeletons[index];
  98797. if (!skeleton.doNotSerialize) {
  98798. serializationObject.skeletons.push(skeleton.serialize());
  98799. }
  98800. }
  98801. // Transform nodes
  98802. serializationObject.transformNodes = [];
  98803. for (index = 0; index < scene.transformNodes.length; index++) {
  98804. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  98805. }
  98806. // Geometries
  98807. serializationObject.geometries = {};
  98808. serializationObject.geometries.boxes = [];
  98809. serializationObject.geometries.spheres = [];
  98810. serializationObject.geometries.cylinders = [];
  98811. serializationObject.geometries.toruses = [];
  98812. serializationObject.geometries.grounds = [];
  98813. serializationObject.geometries.planes = [];
  98814. serializationObject.geometries.torusKnots = [];
  98815. serializationObject.geometries.vertexData = [];
  98816. serializedGeometries = [];
  98817. var geometries = scene.getGeometries();
  98818. for (index = 0; index < geometries.length; index++) {
  98819. var geometry = geometries[index];
  98820. if (geometry.isReady()) {
  98821. serializeGeometry(geometry, serializationObject.geometries);
  98822. }
  98823. }
  98824. // Meshes
  98825. serializationObject.meshes = [];
  98826. for (index = 0; index < scene.meshes.length; index++) {
  98827. var abstractMesh = scene.meshes[index];
  98828. if (abstractMesh instanceof BABYLON.Mesh) {
  98829. var mesh = abstractMesh;
  98830. if (!mesh.doNotSerialize) {
  98831. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98832. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98833. }
  98834. }
  98835. }
  98836. }
  98837. // Particles Systems
  98838. serializationObject.particleSystems = [];
  98839. for (index = 0; index < scene.particleSystems.length; index++) {
  98840. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  98841. }
  98842. // Shadows
  98843. serializationObject.shadowGenerators = [];
  98844. for (index = 0; index < scene.lights.length; index++) {
  98845. light = scene.lights[index];
  98846. var shadowGenerator = light.getShadowGenerator();
  98847. if (shadowGenerator) {
  98848. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  98849. }
  98850. }
  98851. // Action Manager
  98852. if (scene.actionManager) {
  98853. serializationObject.actions = scene.actionManager.serialize("scene");
  98854. }
  98855. // Audio
  98856. serializationObject.sounds = [];
  98857. for (index = 0; index < scene.soundTracks.length; index++) {
  98858. var soundtrack = scene.soundTracks[index];
  98859. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  98860. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  98861. }
  98862. }
  98863. // Components
  98864. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  98865. var component = _c[_b];
  98866. component.serialize(serializationObject);
  98867. }
  98868. return serializationObject;
  98869. };
  98870. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  98871. if (withParents === void 0) { withParents = false; }
  98872. if (withChildren === void 0) { withChildren = false; }
  98873. var serializationObject = {};
  98874. SceneSerializer.ClearCache();
  98875. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  98876. if (withParents || withChildren) {
  98877. //deliberate for loop! not for each, appended should be processed as well.
  98878. for (var i = 0; i < toSerialize.length; ++i) {
  98879. if (withChildren) {
  98880. toSerialize[i].getDescendants().forEach(function (node) {
  98881. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  98882. toSerialize.push(node);
  98883. }
  98884. });
  98885. }
  98886. //make sure the array doesn't contain the object already
  98887. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  98888. toSerialize.push(toSerialize[i].parent);
  98889. }
  98890. }
  98891. }
  98892. toSerialize.forEach(function (mesh) {
  98893. finalizeSingleMesh(mesh, serializationObject);
  98894. });
  98895. return serializationObject;
  98896. };
  98897. return SceneSerializer;
  98898. }());
  98899. BABYLON.SceneSerializer = SceneSerializer;
  98900. })(BABYLON || (BABYLON = {}));
  98901. //# sourceMappingURL=babylon.sceneSerializer.js.map
  98902. var BABYLON;
  98903. (function (BABYLON) {
  98904. var ReflectionProbe = /** @class */ (function () {
  98905. function ReflectionProbe(name, size, scene, generateMipMaps) {
  98906. if (generateMipMaps === void 0) { generateMipMaps = true; }
  98907. var _this = this;
  98908. this.name = name;
  98909. this._viewMatrix = BABYLON.Matrix.Identity();
  98910. this._target = BABYLON.Vector3.Zero();
  98911. this._add = BABYLON.Vector3.Zero();
  98912. this._invertYAxis = false;
  98913. this.position = BABYLON.Vector3.Zero();
  98914. this._scene = scene;
  98915. this._scene.reflectionProbes.push(this);
  98916. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  98917. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  98918. switch (faceIndex) {
  98919. case 0:
  98920. _this._add.copyFromFloats(1, 0, 0);
  98921. break;
  98922. case 1:
  98923. _this._add.copyFromFloats(-1, 0, 0);
  98924. break;
  98925. case 2:
  98926. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  98927. break;
  98928. case 3:
  98929. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  98930. break;
  98931. case 4:
  98932. _this._add.copyFromFloats(0, 0, 1);
  98933. break;
  98934. case 5:
  98935. _this._add.copyFromFloats(0, 0, -1);
  98936. break;
  98937. }
  98938. if (_this._attachedMesh) {
  98939. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  98940. }
  98941. _this.position.addToRef(_this._add, _this._target);
  98942. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  98943. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  98944. scene._forcedViewPosition = _this.position;
  98945. });
  98946. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  98947. scene._forcedViewPosition = null;
  98948. scene.updateTransformMatrix(true);
  98949. });
  98950. if (scene.activeCamera) {
  98951. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  98952. }
  98953. }
  98954. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  98955. get: function () {
  98956. return this._renderTargetTexture.samples;
  98957. },
  98958. set: function (value) {
  98959. this._renderTargetTexture.samples = value;
  98960. },
  98961. enumerable: true,
  98962. configurable: true
  98963. });
  98964. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  98965. get: function () {
  98966. return this._renderTargetTexture.refreshRate;
  98967. },
  98968. set: function (value) {
  98969. this._renderTargetTexture.refreshRate = value;
  98970. },
  98971. enumerable: true,
  98972. configurable: true
  98973. });
  98974. ReflectionProbe.prototype.getScene = function () {
  98975. return this._scene;
  98976. };
  98977. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  98978. get: function () {
  98979. return this._renderTargetTexture;
  98980. },
  98981. enumerable: true,
  98982. configurable: true
  98983. });
  98984. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  98985. get: function () {
  98986. return this._renderTargetTexture.renderList;
  98987. },
  98988. enumerable: true,
  98989. configurable: true
  98990. });
  98991. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  98992. this._attachedMesh = mesh;
  98993. };
  98994. /**
  98995. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  98996. *
  98997. * @param renderingGroupId The rendering group id corresponding to its index
  98998. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  98999. */
  99000. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  99001. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  99002. };
  99003. ReflectionProbe.prototype.dispose = function () {
  99004. var index = this._scene.reflectionProbes.indexOf(this);
  99005. if (index !== -1) {
  99006. // Remove from the scene if found
  99007. this._scene.reflectionProbes.splice(index, 1);
  99008. }
  99009. if (this._renderTargetTexture) {
  99010. this._renderTargetTexture.dispose();
  99011. this._renderTargetTexture = null;
  99012. }
  99013. };
  99014. return ReflectionProbe;
  99015. }());
  99016. BABYLON.ReflectionProbe = ReflectionProbe;
  99017. })(BABYLON || (BABYLON = {}));
  99018. //# sourceMappingURL=babylon.reflectionProbe.js.map
  99019. var BABYLON;
  99020. (function (BABYLON) {
  99021. /**
  99022. * Defines the layer scene component responsible to manage any layers
  99023. * in a given scene.
  99024. */
  99025. var LayerSceneComponent = /** @class */ (function () {
  99026. /**
  99027. * Creates a new instance of the component for the given scene
  99028. * @param scene Defines the scene to register the component in
  99029. */
  99030. function LayerSceneComponent(scene) {
  99031. /**
  99032. * The component name helpfull to identify the component in the list of scene components.
  99033. */
  99034. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  99035. this.scene = scene;
  99036. this._engine = scene.getEngine();
  99037. scene.layers = new Array();
  99038. }
  99039. /**
  99040. * Registers the component in a given scene
  99041. */
  99042. LayerSceneComponent.prototype.register = function () {
  99043. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  99044. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  99045. };
  99046. /**
  99047. * Rebuilds the elements related to this component in case of
  99048. * context lost for instance.
  99049. */
  99050. LayerSceneComponent.prototype.rebuild = function () {
  99051. var layers = this.scene.layers;
  99052. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  99053. var layer = layers_1[_i];
  99054. layer._rebuild();
  99055. }
  99056. };
  99057. /**
  99058. * Disposes the component and the associated ressources.
  99059. */
  99060. LayerSceneComponent.prototype.dispose = function () {
  99061. var layers = this.scene.layers;
  99062. while (layers.length) {
  99063. layers[0].dispose();
  99064. }
  99065. };
  99066. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  99067. var layers = this.scene.layers;
  99068. if (layers.length) {
  99069. this._engine.setDepthBuffer(false);
  99070. var cameraLayerMask = camera.layerMask;
  99071. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  99072. var layer = layers_2[_i];
  99073. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  99074. layer.render();
  99075. }
  99076. }
  99077. this._engine.setDepthBuffer(true);
  99078. }
  99079. };
  99080. LayerSceneComponent.prototype._drawBackground = function (camera) {
  99081. this._draw(camera, true);
  99082. };
  99083. LayerSceneComponent.prototype._drawForeground = function (camera) {
  99084. this._draw(camera, false);
  99085. };
  99086. return LayerSceneComponent;
  99087. }());
  99088. BABYLON.LayerSceneComponent = LayerSceneComponent;
  99089. })(BABYLON || (BABYLON = {}));
  99090. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  99091. var BABYLON;
  99092. (function (BABYLON) {
  99093. var Layer = /** @class */ (function () {
  99094. function Layer(name, imgUrl, scene, isBackground, color) {
  99095. this.name = name;
  99096. this.scale = new BABYLON.Vector2(1, 1);
  99097. this.offset = new BABYLON.Vector2(0, 0);
  99098. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  99099. this.layerMask = 0x0FFFFFFF;
  99100. this._vertexBuffers = {};
  99101. // Events
  99102. /**
  99103. * An event triggered when the layer is disposed.
  99104. */
  99105. this.onDisposeObservable = new BABYLON.Observable();
  99106. /**
  99107. * An event triggered before rendering the scene
  99108. */
  99109. this.onBeforeRenderObservable = new BABYLON.Observable();
  99110. /**
  99111. * An event triggered after rendering the scene
  99112. */
  99113. this.onAfterRenderObservable = new BABYLON.Observable();
  99114. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  99115. this.isBackground = isBackground === undefined ? true : isBackground;
  99116. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  99117. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  99118. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  99119. if (!layerComponent) {
  99120. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  99121. this._scene._addComponent(layerComponent);
  99122. }
  99123. this._scene.layers.push(this);
  99124. var engine = this._scene.getEngine();
  99125. // VBO
  99126. var vertices = [];
  99127. vertices.push(1, 1);
  99128. vertices.push(-1, 1);
  99129. vertices.push(-1, -1);
  99130. vertices.push(1, -1);
  99131. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  99132. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  99133. this._createIndexBuffer();
  99134. // Effects
  99135. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  99136. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  99137. }
  99138. Object.defineProperty(Layer.prototype, "onDispose", {
  99139. set: function (callback) {
  99140. if (this._onDisposeObserver) {
  99141. this.onDisposeObservable.remove(this._onDisposeObserver);
  99142. }
  99143. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  99144. },
  99145. enumerable: true,
  99146. configurable: true
  99147. });
  99148. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  99149. set: function (callback) {
  99150. if (this._onBeforeRenderObserver) {
  99151. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  99152. }
  99153. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  99154. },
  99155. enumerable: true,
  99156. configurable: true
  99157. });
  99158. Object.defineProperty(Layer.prototype, "onAfterRender", {
  99159. set: function (callback) {
  99160. if (this._onAfterRenderObserver) {
  99161. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  99162. }
  99163. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  99164. },
  99165. enumerable: true,
  99166. configurable: true
  99167. });
  99168. Layer.prototype._createIndexBuffer = function () {
  99169. var engine = this._scene.getEngine();
  99170. // Indices
  99171. var indices = [];
  99172. indices.push(0);
  99173. indices.push(1);
  99174. indices.push(2);
  99175. indices.push(0);
  99176. indices.push(2);
  99177. indices.push(3);
  99178. this._indexBuffer = engine.createIndexBuffer(indices);
  99179. };
  99180. Layer.prototype._rebuild = function () {
  99181. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99182. if (vb) {
  99183. vb._rebuild();
  99184. }
  99185. this._createIndexBuffer();
  99186. };
  99187. Layer.prototype.render = function () {
  99188. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  99189. // Check
  99190. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  99191. return;
  99192. var engine = this._scene.getEngine();
  99193. this.onBeforeRenderObservable.notifyObservers(this);
  99194. // Render
  99195. engine.enableEffect(currentEffect);
  99196. engine.setState(false);
  99197. // Texture
  99198. currentEffect.setTexture("textureSampler", this.texture);
  99199. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  99200. // Color
  99201. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  99202. // Scale / offset
  99203. currentEffect.setVector2("offset", this.offset);
  99204. currentEffect.setVector2("scale", this.scale);
  99205. // VBOs
  99206. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  99207. // Draw order
  99208. if (!this.alphaTest) {
  99209. engine.setAlphaMode(this.alphaBlendingMode);
  99210. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99211. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  99212. }
  99213. else {
  99214. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99215. }
  99216. this.onAfterRenderObservable.notifyObservers(this);
  99217. };
  99218. Layer.prototype.dispose = function () {
  99219. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99220. if (vertexBuffer) {
  99221. vertexBuffer.dispose();
  99222. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  99223. }
  99224. if (this._indexBuffer) {
  99225. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  99226. this._indexBuffer = null;
  99227. }
  99228. if (this.texture) {
  99229. this.texture.dispose();
  99230. this.texture = null;
  99231. }
  99232. // Remove from scene
  99233. var index = this._scene.layers.indexOf(this);
  99234. this._scene.layers.splice(index, 1);
  99235. // Callback
  99236. this.onDisposeObservable.notifyObservers(this);
  99237. this.onDisposeObservable.clear();
  99238. this.onAfterRenderObservable.clear();
  99239. this.onBeforeRenderObservable.clear();
  99240. };
  99241. return Layer;
  99242. }());
  99243. BABYLON.Layer = Layer;
  99244. })(BABYLON || (BABYLON = {}));
  99245. //# sourceMappingURL=babylon.layer.js.map
  99246. var BABYLON;
  99247. (function (BABYLON) {
  99248. var TextureTools = /** @class */ (function () {
  99249. function TextureTools() {
  99250. }
  99251. /**
  99252. * Uses the GPU to create a copy texture rescaled at a given size
  99253. * @param texture Texture to copy from
  99254. * @param width Desired width
  99255. * @param height Desired height
  99256. * @return Generated texture
  99257. */
  99258. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  99259. if (useBilinearMode === void 0) { useBilinearMode = true; }
  99260. var scene = texture.getScene();
  99261. var engine = scene.getEngine();
  99262. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  99263. rtt.wrapU = texture.wrapU;
  99264. rtt.wrapV = texture.wrapV;
  99265. rtt.uOffset = texture.uOffset;
  99266. rtt.vOffset = texture.vOffset;
  99267. rtt.uScale = texture.uScale;
  99268. rtt.vScale = texture.vScale;
  99269. rtt.uAng = texture.uAng;
  99270. rtt.vAng = texture.vAng;
  99271. rtt.wAng = texture.wAng;
  99272. rtt.coordinatesIndex = texture.coordinatesIndex;
  99273. rtt.level = texture.level;
  99274. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  99275. rtt._texture.isReady = false;
  99276. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99277. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99278. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  99279. passPostProcess.getEffect().executeWhenCompiled(function () {
  99280. passPostProcess.onApply = function (effect) {
  99281. effect.setTexture("textureSampler", texture);
  99282. };
  99283. var internalTexture = rtt.getInternalTexture();
  99284. if (internalTexture) {
  99285. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  99286. engine.unBindFramebuffer(internalTexture);
  99287. rtt.disposeFramebufferObjects();
  99288. passPostProcess.dispose();
  99289. internalTexture.isReady = true;
  99290. }
  99291. });
  99292. return rtt;
  99293. };
  99294. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  99295. if (!scene._environmentBRDFTexture) {
  99296. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  99297. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99298. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99299. scene._environmentBRDFTexture = texture;
  99300. }
  99301. return scene._environmentBRDFTexture;
  99302. };
  99303. 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=";
  99304. return TextureTools;
  99305. }());
  99306. BABYLON.TextureTools = TextureTools;
  99307. })(BABYLON || (BABYLON = {}));
  99308. //# sourceMappingURL=babylon.textureTools.js.map
  99309. var BABYLON;
  99310. (function (BABYLON) {
  99311. var FramingBehavior = /** @class */ (function () {
  99312. function FramingBehavior() {
  99313. this._mode = FramingBehavior.FitFrustumSidesMode;
  99314. this._radiusScale = 1.0;
  99315. this._positionScale = 0.5;
  99316. this._defaultElevation = 0.3;
  99317. this._elevationReturnTime = 1500;
  99318. this._elevationReturnWaitTime = 1000;
  99319. this._zoomStopsAnimation = false;
  99320. this._framingTime = 1500;
  99321. this._isPointerDown = false;
  99322. this._lastInteractionTime = -Infinity;
  99323. // Framing control
  99324. this._animatables = new Array();
  99325. this._betaIsAnimating = false;
  99326. }
  99327. Object.defineProperty(FramingBehavior.prototype, "name", {
  99328. get: function () {
  99329. return "Framing";
  99330. },
  99331. enumerable: true,
  99332. configurable: true
  99333. });
  99334. Object.defineProperty(FramingBehavior.prototype, "mode", {
  99335. /**
  99336. * Gets current mode used by the behavior.
  99337. */
  99338. get: function () {
  99339. return this._mode;
  99340. },
  99341. /**
  99342. * Sets the current mode used by the behavior
  99343. */
  99344. set: function (mode) {
  99345. this._mode = mode;
  99346. },
  99347. enumerable: true,
  99348. configurable: true
  99349. });
  99350. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  99351. /**
  99352. * Gets the scale applied to the radius
  99353. */
  99354. get: function () {
  99355. return this._radiusScale;
  99356. },
  99357. /**
  99358. * Sets the scale applied to the radius (1 by default)
  99359. */
  99360. set: function (radius) {
  99361. this._radiusScale = radius;
  99362. },
  99363. enumerable: true,
  99364. configurable: true
  99365. });
  99366. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  99367. /**
  99368. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99369. */
  99370. get: function () {
  99371. return this._positionScale;
  99372. },
  99373. /**
  99374. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99375. */
  99376. set: function (scale) {
  99377. this._positionScale = scale;
  99378. },
  99379. enumerable: true,
  99380. configurable: true
  99381. });
  99382. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  99383. /**
  99384. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99385. * behaviour is triggered, in radians.
  99386. */
  99387. get: function () {
  99388. return this._defaultElevation;
  99389. },
  99390. /**
  99391. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99392. * behaviour is triggered, in radians.
  99393. */
  99394. set: function (elevation) {
  99395. this._defaultElevation = elevation;
  99396. },
  99397. enumerable: true,
  99398. configurable: true
  99399. });
  99400. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  99401. /**
  99402. * Gets the time (in milliseconds) taken to return to the default beta position.
  99403. * Negative value indicates camera should not return to default.
  99404. */
  99405. get: function () {
  99406. return this._elevationReturnTime;
  99407. },
  99408. /**
  99409. * Sets the time (in milliseconds) taken to return to the default beta position.
  99410. * Negative value indicates camera should not return to default.
  99411. */
  99412. set: function (speed) {
  99413. this._elevationReturnTime = speed;
  99414. },
  99415. enumerable: true,
  99416. configurable: true
  99417. });
  99418. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  99419. /**
  99420. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99421. */
  99422. get: function () {
  99423. return this._elevationReturnWaitTime;
  99424. },
  99425. /**
  99426. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99427. */
  99428. set: function (time) {
  99429. this._elevationReturnWaitTime = time;
  99430. },
  99431. enumerable: true,
  99432. configurable: true
  99433. });
  99434. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  99435. /**
  99436. * Gets the flag that indicates if user zooming should stop animation.
  99437. */
  99438. get: function () {
  99439. return this._zoomStopsAnimation;
  99440. },
  99441. /**
  99442. * Sets the flag that indicates if user zooming should stop animation.
  99443. */
  99444. set: function (flag) {
  99445. this._zoomStopsAnimation = flag;
  99446. },
  99447. enumerable: true,
  99448. configurable: true
  99449. });
  99450. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  99451. /**
  99452. * Gets the transition time when framing the mesh, in milliseconds
  99453. */
  99454. get: function () {
  99455. return this._framingTime;
  99456. },
  99457. /**
  99458. * Sets the transition time when framing the mesh, in milliseconds
  99459. */
  99460. set: function (time) {
  99461. this._framingTime = time;
  99462. },
  99463. enumerable: true,
  99464. configurable: true
  99465. });
  99466. FramingBehavior.prototype.init = function () {
  99467. // Do notihng
  99468. };
  99469. FramingBehavior.prototype.attach = function (camera) {
  99470. var _this = this;
  99471. this._attachedCamera = camera;
  99472. var scene = this._attachedCamera.getScene();
  99473. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  99474. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  99475. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99476. _this._isPointerDown = true;
  99477. return;
  99478. }
  99479. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  99480. _this._isPointerDown = false;
  99481. }
  99482. });
  99483. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99484. if (mesh) {
  99485. _this.zoomOnMesh(mesh);
  99486. }
  99487. });
  99488. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99489. // Stop the animation if there is user interaction and the animation should stop for this interaction
  99490. _this._applyUserInteraction();
  99491. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  99492. // back to the default position after a given timeout
  99493. _this._maintainCameraAboveGround();
  99494. });
  99495. };
  99496. FramingBehavior.prototype.detach = function () {
  99497. if (!this._attachedCamera) {
  99498. return;
  99499. }
  99500. var scene = this._attachedCamera.getScene();
  99501. if (this._onPrePointerObservableObserver) {
  99502. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  99503. }
  99504. if (this._onAfterCheckInputsObserver) {
  99505. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99506. }
  99507. if (this._onMeshTargetChangedObserver) {
  99508. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99509. }
  99510. this._attachedCamera = null;
  99511. };
  99512. /**
  99513. * Targets the given mesh and updates zoom level accordingly.
  99514. * @param mesh The mesh to target.
  99515. * @param radius Optional. If a cached radius position already exists, overrides default.
  99516. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99517. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99518. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99519. */
  99520. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99521. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99522. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99523. mesh.computeWorldMatrix(true);
  99524. var boundingBox = mesh.getBoundingInfo().boundingBox;
  99525. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  99526. };
  99527. /**
  99528. * Targets the given mesh with its children and updates zoom level accordingly.
  99529. * @param mesh The mesh to target.
  99530. * @param radius Optional. If a cached radius position already exists, overrides default.
  99531. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99532. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99533. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99534. */
  99535. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99536. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99537. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99538. mesh.computeWorldMatrix(true);
  99539. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  99540. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  99541. };
  99542. /**
  99543. * Targets the given meshes with their children and updates zoom level accordingly.
  99544. * @param meshes The mesh to target.
  99545. * @param radius Optional. If a cached radius position already exists, overrides default.
  99546. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99547. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99548. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99549. */
  99550. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  99551. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99552. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99553. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  99554. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  99555. for (var i = 0; i < meshes.length; i++) {
  99556. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  99557. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  99558. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  99559. }
  99560. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  99561. };
  99562. /**
  99563. * Targets the given mesh and updates zoom level accordingly.
  99564. * @param mesh The mesh to target.
  99565. * @param radius Optional. If a cached radius position already exists, overrides default.
  99566. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99567. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99568. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99569. */
  99570. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  99571. var _this = this;
  99572. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99573. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99574. var zoomTarget;
  99575. if (!this._attachedCamera) {
  99576. return;
  99577. }
  99578. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  99579. var bottom = minimumWorld.y;
  99580. var top = maximumWorld.y;
  99581. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  99582. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  99583. if (focusOnOriginXZ) {
  99584. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  99585. }
  99586. else {
  99587. var centerWorld = minimumWorld.add(radiusWorld);
  99588. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  99589. }
  99590. if (!this._vectorTransition) {
  99591. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  99592. }
  99593. this._betaIsAnimating = true;
  99594. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  99595. if (animatable) {
  99596. this._animatables.push(animatable);
  99597. }
  99598. // sets the radius and lower radius bounds
  99599. // Small delta ensures camera is not always at lower zoom limit.
  99600. var radius = 0;
  99601. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  99602. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99603. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  99604. radius = position;
  99605. }
  99606. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99607. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99608. if (this._attachedCamera.lowerRadiusLimit === null) {
  99609. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  99610. }
  99611. }
  99612. // Set sensibilities
  99613. var extend = maximumWorld.subtract(minimumWorld).length();
  99614. this._attachedCamera.panningSensibility = 5000 / extend;
  99615. this._attachedCamera.wheelPrecision = 100 / radius;
  99616. // transition to new radius
  99617. if (!this._radiusTransition) {
  99618. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99619. }
  99620. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  99621. _this.stopAllAnimations();
  99622. if (onAnimationEnd) {
  99623. onAnimationEnd();
  99624. }
  99625. if (_this._attachedCamera) {
  99626. _this._attachedCamera.storeState();
  99627. }
  99628. });
  99629. if (animatable) {
  99630. this._animatables.push(animatable);
  99631. }
  99632. };
  99633. /**
  99634. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  99635. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  99636. * frustum width.
  99637. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  99638. * to fully enclose the mesh in the viewing frustum.
  99639. */
  99640. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  99641. var size = maximumWorld.subtract(minimumWorld);
  99642. var boxVectorGlobalDiagonal = size.length();
  99643. var frustumSlope = this._getFrustumSlope();
  99644. // Formula for setting distance
  99645. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  99646. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  99647. // Horizon distance
  99648. var radius = radiusWithoutFraming * this._radiusScale;
  99649. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  99650. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  99651. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  99652. var camera = this._attachedCamera;
  99653. if (!camera) {
  99654. return 0;
  99655. }
  99656. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99657. // Don't exceed the requested limit
  99658. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  99659. }
  99660. // Don't exceed the upper radius limit
  99661. if (camera.upperRadiusLimit) {
  99662. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  99663. }
  99664. return distance;
  99665. };
  99666. /**
  99667. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  99668. * is automatically returned to its default position (expected to be above ground plane).
  99669. */
  99670. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  99671. var _this = this;
  99672. if (this._elevationReturnTime < 0) {
  99673. return;
  99674. }
  99675. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  99676. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  99677. var limitBeta = Math.PI * 0.5;
  99678. // Bring the camera back up if below the ground plane
  99679. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  99680. this._betaIsAnimating = true;
  99681. //Transition to new position
  99682. this.stopAllAnimations();
  99683. if (!this._betaTransition) {
  99684. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99685. }
  99686. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  99687. _this._clearAnimationLocks();
  99688. _this.stopAllAnimations();
  99689. });
  99690. if (animatabe) {
  99691. this._animatables.push(animatabe);
  99692. }
  99693. }
  99694. };
  99695. /**
  99696. * Returns the frustum slope based on the canvas ratio and camera FOV
  99697. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  99698. */
  99699. FramingBehavior.prototype._getFrustumSlope = function () {
  99700. // Calculate the viewport ratio
  99701. // Aspect Ratio is Height/Width.
  99702. var camera = this._attachedCamera;
  99703. if (!camera) {
  99704. return BABYLON.Vector2.Zero();
  99705. }
  99706. var engine = camera.getScene().getEngine();
  99707. var aspectRatio = engine.getAspectRatio(camera);
  99708. // Camera FOV is the vertical field of view (top-bottom) in radians.
  99709. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  99710. var frustumSlopeY = Math.tan(camera.fov / 2);
  99711. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  99712. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  99713. // along the forward vector.
  99714. var frustumSlopeX = frustumSlopeY * aspectRatio;
  99715. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  99716. };
  99717. /**
  99718. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  99719. */
  99720. FramingBehavior.prototype._clearAnimationLocks = function () {
  99721. this._betaIsAnimating = false;
  99722. };
  99723. /**
  99724. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  99725. */
  99726. FramingBehavior.prototype._applyUserInteraction = function () {
  99727. if (this.isUserIsMoving) {
  99728. this._lastInteractionTime = BABYLON.Tools.Now;
  99729. this.stopAllAnimations();
  99730. this._clearAnimationLocks();
  99731. }
  99732. };
  99733. /**
  99734. * Stops and removes all animations that have been applied to the camera
  99735. */
  99736. FramingBehavior.prototype.stopAllAnimations = function () {
  99737. if (this._attachedCamera) {
  99738. this._attachedCamera.animations = [];
  99739. }
  99740. while (this._animatables.length) {
  99741. if (this._animatables[0]) {
  99742. this._animatables[0].onAnimationEnd = null;
  99743. this._animatables[0].stop();
  99744. }
  99745. this._animatables.shift();
  99746. }
  99747. };
  99748. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  99749. /**
  99750. * Gets a value indicating if the user is moving the camera
  99751. */
  99752. get: function () {
  99753. if (!this._attachedCamera) {
  99754. return false;
  99755. }
  99756. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  99757. this._attachedCamera.inertialBetaOffset !== 0 ||
  99758. this._attachedCamera.inertialRadiusOffset !== 0 ||
  99759. this._attachedCamera.inertialPanningX !== 0 ||
  99760. this._attachedCamera.inertialPanningY !== 0 ||
  99761. this._isPointerDown;
  99762. },
  99763. enumerable: true,
  99764. configurable: true
  99765. });
  99766. /**
  99767. * The easing function used by animations
  99768. */
  99769. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  99770. /**
  99771. * The easing mode used by animations
  99772. */
  99773. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  99774. // Statics
  99775. /**
  99776. * The camera can move all the way towards the mesh.
  99777. */
  99778. FramingBehavior.IgnoreBoundsSizeMode = 0;
  99779. /**
  99780. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  99781. */
  99782. FramingBehavior.FitFrustumSidesMode = 1;
  99783. return FramingBehavior;
  99784. }());
  99785. BABYLON.FramingBehavior = FramingBehavior;
  99786. })(BABYLON || (BABYLON = {}));
  99787. //# sourceMappingURL=babylon.framingBehavior.js.map
  99788. var BABYLON;
  99789. (function (BABYLON) {
  99790. /**
  99791. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  99792. */
  99793. var BouncingBehavior = /** @class */ (function () {
  99794. function BouncingBehavior() {
  99795. /**
  99796. * The duration of the animation, in milliseconds
  99797. */
  99798. this.transitionDuration = 450;
  99799. /**
  99800. * Length of the distance animated by the transition when lower radius is reached
  99801. */
  99802. this.lowerRadiusTransitionRange = 2;
  99803. /**
  99804. * Length of the distance animated by the transition when upper radius is reached
  99805. */
  99806. this.upperRadiusTransitionRange = -2;
  99807. this._autoTransitionRange = false;
  99808. // Animations
  99809. this._radiusIsAnimating = false;
  99810. this._radiusBounceTransition = null;
  99811. this._animatables = new Array();
  99812. }
  99813. Object.defineProperty(BouncingBehavior.prototype, "name", {
  99814. get: function () {
  99815. return "Bouncing";
  99816. },
  99817. enumerable: true,
  99818. configurable: true
  99819. });
  99820. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  99821. /**
  99822. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  99823. */
  99824. get: function () {
  99825. return this._autoTransitionRange;
  99826. },
  99827. /**
  99828. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  99829. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  99830. */
  99831. set: function (value) {
  99832. var _this = this;
  99833. if (this._autoTransitionRange === value) {
  99834. return;
  99835. }
  99836. this._autoTransitionRange = value;
  99837. var camera = this._attachedCamera;
  99838. if (!camera) {
  99839. return;
  99840. }
  99841. if (value) {
  99842. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99843. if (!mesh) {
  99844. return;
  99845. }
  99846. mesh.computeWorldMatrix(true);
  99847. var diagonal = mesh.getBoundingInfo().diagonalLength;
  99848. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  99849. _this.upperRadiusTransitionRange = diagonal * 0.05;
  99850. });
  99851. }
  99852. else if (this._onMeshTargetChangedObserver) {
  99853. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99854. }
  99855. },
  99856. enumerable: true,
  99857. configurable: true
  99858. });
  99859. BouncingBehavior.prototype.init = function () {
  99860. // Do notihng
  99861. };
  99862. BouncingBehavior.prototype.attach = function (camera) {
  99863. var _this = this;
  99864. this._attachedCamera = camera;
  99865. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99866. if (!_this._attachedCamera) {
  99867. return;
  99868. }
  99869. // Add the bounce animation to the lower radius limit
  99870. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  99871. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  99872. }
  99873. // Add the bounce animation to the upper radius limit
  99874. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  99875. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  99876. }
  99877. });
  99878. };
  99879. BouncingBehavior.prototype.detach = function () {
  99880. if (!this._attachedCamera) {
  99881. return;
  99882. }
  99883. if (this._onAfterCheckInputsObserver) {
  99884. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99885. }
  99886. if (this._onMeshTargetChangedObserver) {
  99887. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99888. }
  99889. this._attachedCamera = null;
  99890. };
  99891. /**
  99892. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  99893. * @param radiusLimit The limit to check against.
  99894. * @return Bool to indicate if at limit.
  99895. */
  99896. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  99897. if (!this._attachedCamera) {
  99898. return false;
  99899. }
  99900. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  99901. return true;
  99902. }
  99903. return false;
  99904. };
  99905. /**
  99906. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  99907. * @param radiusDelta The delta by which to animate to. Can be negative.
  99908. */
  99909. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  99910. var _this = this;
  99911. if (!this._attachedCamera) {
  99912. return;
  99913. }
  99914. if (!this._radiusBounceTransition) {
  99915. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  99916. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  99917. }
  99918. // Prevent zoom until bounce has completed
  99919. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  99920. this._attachedCamera.wheelPrecision = Infinity;
  99921. this._attachedCamera.inertialRadiusOffset = 0;
  99922. // Animate to the radius limit
  99923. this.stopAllAnimations();
  99924. this._radiusIsAnimating = true;
  99925. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  99926. if (animatable) {
  99927. this._animatables.push(animatable);
  99928. }
  99929. };
  99930. /**
  99931. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  99932. */
  99933. BouncingBehavior.prototype._clearAnimationLocks = function () {
  99934. this._radiusIsAnimating = false;
  99935. if (this._attachedCamera) {
  99936. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  99937. }
  99938. };
  99939. /**
  99940. * Stops and removes all animations that have been applied to the camera
  99941. */
  99942. BouncingBehavior.prototype.stopAllAnimations = function () {
  99943. if (this._attachedCamera) {
  99944. this._attachedCamera.animations = [];
  99945. }
  99946. while (this._animatables.length) {
  99947. this._animatables[0].onAnimationEnd = null;
  99948. this._animatables[0].stop();
  99949. this._animatables.shift();
  99950. }
  99951. };
  99952. /**
  99953. * The easing function used by animations
  99954. */
  99955. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  99956. /**
  99957. * The easing mode used by animations
  99958. */
  99959. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  99960. return BouncingBehavior;
  99961. }());
  99962. BABYLON.BouncingBehavior = BouncingBehavior;
  99963. })(BABYLON || (BABYLON = {}));
  99964. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  99965. var BABYLON;
  99966. (function (BABYLON) {
  99967. var AutoRotationBehavior = /** @class */ (function () {
  99968. function AutoRotationBehavior() {
  99969. this._zoomStopsAnimation = false;
  99970. this._idleRotationSpeed = 0.05;
  99971. this._idleRotationWaitTime = 2000;
  99972. this._idleRotationSpinupTime = 2000;
  99973. this._isPointerDown = false;
  99974. this._lastFrameTime = null;
  99975. this._lastInteractionTime = -Infinity;
  99976. this._cameraRotationSpeed = 0;
  99977. this._lastFrameRadius = 0;
  99978. }
  99979. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  99980. get: function () {
  99981. return "AutoRotation";
  99982. },
  99983. enumerable: true,
  99984. configurable: true
  99985. });
  99986. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  99987. /**
  99988. * Gets the flag that indicates if user zooming should stop animation.
  99989. */
  99990. get: function () {
  99991. return this._zoomStopsAnimation;
  99992. },
  99993. /**
  99994. * Sets the flag that indicates if user zooming should stop animation.
  99995. */
  99996. set: function (flag) {
  99997. this._zoomStopsAnimation = flag;
  99998. },
  99999. enumerable: true,
  100000. configurable: true
  100001. });
  100002. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  100003. /**
  100004. * Gets the default speed at which the camera rotates around the model.
  100005. */
  100006. get: function () {
  100007. return this._idleRotationSpeed;
  100008. },
  100009. /**
  100010. * Sets the default speed at which the camera rotates around the model.
  100011. */
  100012. set: function (speed) {
  100013. this._idleRotationSpeed = speed;
  100014. },
  100015. enumerable: true,
  100016. configurable: true
  100017. });
  100018. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  100019. /**
  100020. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  100021. */
  100022. get: function () {
  100023. return this._idleRotationWaitTime;
  100024. },
  100025. /**
  100026. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  100027. */
  100028. set: function (time) {
  100029. this._idleRotationWaitTime = time;
  100030. },
  100031. enumerable: true,
  100032. configurable: true
  100033. });
  100034. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  100035. /**
  100036. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100037. */
  100038. get: function () {
  100039. return this._idleRotationSpinupTime;
  100040. },
  100041. /**
  100042. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100043. */
  100044. set: function (time) {
  100045. this._idleRotationSpinupTime = time;
  100046. },
  100047. enumerable: true,
  100048. configurable: true
  100049. });
  100050. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  100051. /**
  100052. * Gets a value indicating if the camera is currently rotating because of this behavior
  100053. */
  100054. get: function () {
  100055. return Math.abs(this._cameraRotationSpeed) > 0;
  100056. },
  100057. enumerable: true,
  100058. configurable: true
  100059. });
  100060. AutoRotationBehavior.prototype.init = function () {
  100061. // Do notihng
  100062. };
  100063. AutoRotationBehavior.prototype.attach = function (camera) {
  100064. var _this = this;
  100065. this._attachedCamera = camera;
  100066. var scene = this._attachedCamera.getScene();
  100067. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  100068. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100069. _this._isPointerDown = true;
  100070. return;
  100071. }
  100072. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  100073. _this._isPointerDown = false;
  100074. }
  100075. });
  100076. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100077. var now = BABYLON.Tools.Now;
  100078. var dt = 0;
  100079. if (_this._lastFrameTime != null) {
  100080. dt = now - _this._lastFrameTime;
  100081. }
  100082. _this._lastFrameTime = now;
  100083. // Stop the animation if there is user interaction and the animation should stop for this interaction
  100084. _this._applyUserInteraction();
  100085. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  100086. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  100087. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  100088. // Step camera rotation by rotation speed
  100089. if (_this._attachedCamera) {
  100090. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  100091. }
  100092. });
  100093. };
  100094. AutoRotationBehavior.prototype.detach = function () {
  100095. if (!this._attachedCamera) {
  100096. return;
  100097. }
  100098. var scene = this._attachedCamera.getScene();
  100099. if (this._onPrePointerObservableObserver) {
  100100. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  100101. }
  100102. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100103. this._attachedCamera = null;
  100104. };
  100105. /**
  100106. * Returns true if user is scrolling.
  100107. * @return true if user is scrolling.
  100108. */
  100109. AutoRotationBehavior.prototype._userIsZooming = function () {
  100110. if (!this._attachedCamera) {
  100111. return false;
  100112. }
  100113. return this._attachedCamera.inertialRadiusOffset !== 0;
  100114. };
  100115. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  100116. if (!this._attachedCamera) {
  100117. return false;
  100118. }
  100119. var zoomHasHitLimit = false;
  100120. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  100121. zoomHasHitLimit = true;
  100122. }
  100123. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  100124. this._lastFrameRadius = this._attachedCamera.radius;
  100125. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  100126. };
  100127. /**
  100128. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  100129. */
  100130. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  100131. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  100132. this._lastInteractionTime = BABYLON.Tools.Now;
  100133. }
  100134. };
  100135. // Tools
  100136. AutoRotationBehavior.prototype._userIsMoving = function () {
  100137. if (!this._attachedCamera) {
  100138. return false;
  100139. }
  100140. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  100141. this._attachedCamera.inertialBetaOffset !== 0 ||
  100142. this._attachedCamera.inertialRadiusOffset !== 0 ||
  100143. this._attachedCamera.inertialPanningX !== 0 ||
  100144. this._attachedCamera.inertialPanningY !== 0 ||
  100145. this._isPointerDown;
  100146. };
  100147. return AutoRotationBehavior;
  100148. }());
  100149. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  100150. })(BABYLON || (BABYLON = {}));
  100151. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  100152. var BABYLON;
  100153. (function (BABYLON) {
  100154. var NullEngineOptions = /** @class */ (function () {
  100155. function NullEngineOptions() {
  100156. this.renderWidth = 512;
  100157. this.renderHeight = 256;
  100158. this.textureSize = 512;
  100159. this.deterministicLockstep = false;
  100160. this.lockstepMaxSteps = 4;
  100161. }
  100162. return NullEngineOptions;
  100163. }());
  100164. BABYLON.NullEngineOptions = NullEngineOptions;
  100165. /**
  100166. * The null engine class provides support for headless version of babylon.js.
  100167. * This can be used in server side scenario or for testing purposes
  100168. */
  100169. var NullEngine = /** @class */ (function (_super) {
  100170. __extends(NullEngine, _super);
  100171. function NullEngine(options) {
  100172. if (options === void 0) { options = new NullEngineOptions(); }
  100173. var _this = _super.call(this, null) || this;
  100174. if (options.deterministicLockstep === undefined) {
  100175. options.deterministicLockstep = false;
  100176. }
  100177. if (options.lockstepMaxSteps === undefined) {
  100178. options.lockstepMaxSteps = 4;
  100179. }
  100180. _this._options = options;
  100181. // Init caps
  100182. // We consider we are on a webgl1 capable device
  100183. _this._caps = new BABYLON.EngineCapabilities();
  100184. _this._caps.maxTexturesImageUnits = 16;
  100185. _this._caps.maxVertexTextureImageUnits = 16;
  100186. _this._caps.maxTextureSize = 512;
  100187. _this._caps.maxCubemapTextureSize = 512;
  100188. _this._caps.maxRenderTextureSize = 512;
  100189. _this._caps.maxVertexAttribs = 16;
  100190. _this._caps.maxVaryingVectors = 16;
  100191. _this._caps.maxFragmentUniformVectors = 16;
  100192. _this._caps.maxVertexUniformVectors = 16;
  100193. // Extensions
  100194. _this._caps.standardDerivatives = false;
  100195. _this._caps.astc = null;
  100196. _this._caps.s3tc = null;
  100197. _this._caps.pvrtc = null;
  100198. _this._caps.etc1 = null;
  100199. _this._caps.etc2 = null;
  100200. _this._caps.textureAnisotropicFilterExtension = null;
  100201. _this._caps.maxAnisotropy = 0;
  100202. _this._caps.uintIndices = false;
  100203. _this._caps.fragmentDepthSupported = false;
  100204. _this._caps.highPrecisionShaderSupported = true;
  100205. _this._caps.colorBufferFloat = false;
  100206. _this._caps.textureFloat = false;
  100207. _this._caps.textureFloatLinearFiltering = false;
  100208. _this._caps.textureFloatRender = false;
  100209. _this._caps.textureHalfFloat = false;
  100210. _this._caps.textureHalfFloatLinearFiltering = false;
  100211. _this._caps.textureHalfFloatRender = false;
  100212. _this._caps.textureLOD = false;
  100213. _this._caps.drawBuffersExtension = false;
  100214. _this._caps.depthTextureExtension = false;
  100215. _this._caps.vertexArrayObject = false;
  100216. _this._caps.instancedArrays = false;
  100217. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  100218. // Wrappers
  100219. if (typeof URL === "undefined") {
  100220. URL = {
  100221. createObjectURL: function () { },
  100222. revokeObjectURL: function () { }
  100223. };
  100224. }
  100225. if (typeof Blob === "undefined") {
  100226. Blob = function () { };
  100227. }
  100228. return _this;
  100229. }
  100230. NullEngine.prototype.isDeterministicLockStep = function () {
  100231. return this._options.deterministicLockstep;
  100232. };
  100233. NullEngine.prototype.getLockstepMaxSteps = function () {
  100234. return this._options.lockstepMaxSteps;
  100235. };
  100236. NullEngine.prototype.getHardwareScalingLevel = function () {
  100237. return 1.0;
  100238. };
  100239. NullEngine.prototype.createVertexBuffer = function (vertices) {
  100240. return {
  100241. capacity: 0,
  100242. references: 1,
  100243. is32Bits: false
  100244. };
  100245. };
  100246. NullEngine.prototype.createIndexBuffer = function (indices) {
  100247. return {
  100248. capacity: 0,
  100249. references: 1,
  100250. is32Bits: false
  100251. };
  100252. };
  100253. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  100254. if (stencil === void 0) { stencil = false; }
  100255. };
  100256. NullEngine.prototype.getRenderWidth = function (useScreen) {
  100257. if (useScreen === void 0) { useScreen = false; }
  100258. if (!useScreen && this._currentRenderTarget) {
  100259. return this._currentRenderTarget.width;
  100260. }
  100261. return this._options.renderWidth;
  100262. };
  100263. NullEngine.prototype.getRenderHeight = function (useScreen) {
  100264. if (useScreen === void 0) { useScreen = false; }
  100265. if (!useScreen && this._currentRenderTarget) {
  100266. return this._currentRenderTarget.height;
  100267. }
  100268. return this._options.renderHeight;
  100269. };
  100270. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  100271. this._cachedViewport = viewport;
  100272. };
  100273. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  100274. return {
  100275. transformFeedback: null,
  100276. __SPECTOR_rebuildProgram: null
  100277. };
  100278. };
  100279. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  100280. return [];
  100281. };
  100282. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  100283. return [];
  100284. };
  100285. NullEngine.prototype.bindSamplers = function (effect) {
  100286. this._currentEffect = null;
  100287. };
  100288. NullEngine.prototype.enableEffect = function (effect) {
  100289. this._currentEffect = effect;
  100290. if (effect.onBind) {
  100291. effect.onBind(effect);
  100292. }
  100293. effect.onBindObservable.notifyObservers(effect);
  100294. };
  100295. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  100296. if (zOffset === void 0) { zOffset = 0; }
  100297. if (reverseSide === void 0) { reverseSide = false; }
  100298. };
  100299. NullEngine.prototype.setIntArray = function (uniform, array) {
  100300. };
  100301. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  100302. };
  100303. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  100304. };
  100305. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  100306. };
  100307. NullEngine.prototype.setFloatArray = function (uniform, array) {
  100308. };
  100309. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  100310. };
  100311. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  100312. };
  100313. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  100314. };
  100315. NullEngine.prototype.setArray = function (uniform, array) {
  100316. };
  100317. NullEngine.prototype.setArray2 = function (uniform, array) {
  100318. };
  100319. NullEngine.prototype.setArray3 = function (uniform, array) {
  100320. };
  100321. NullEngine.prototype.setArray4 = function (uniform, array) {
  100322. };
  100323. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  100324. };
  100325. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  100326. };
  100327. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  100328. };
  100329. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  100330. };
  100331. NullEngine.prototype.setFloat = function (uniform, value) {
  100332. };
  100333. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  100334. };
  100335. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  100336. };
  100337. NullEngine.prototype.setBool = function (uniform, bool) {
  100338. };
  100339. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  100340. };
  100341. NullEngine.prototype.setColor3 = function (uniform, color3) {
  100342. };
  100343. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  100344. };
  100345. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  100346. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  100347. if (this._alphaMode === mode) {
  100348. return;
  100349. }
  100350. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  100351. if (!noDepthWriteChange) {
  100352. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  100353. }
  100354. this._alphaMode = mode;
  100355. };
  100356. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  100357. };
  100358. NullEngine.prototype.wipeCaches = function (bruteForce) {
  100359. if (this.preventCacheWipeBetweenFrames) {
  100360. return;
  100361. }
  100362. this.resetTextureCache();
  100363. this._currentEffect = null;
  100364. if (bruteForce) {
  100365. this._currentProgram = null;
  100366. this._stencilState.reset();
  100367. this._depthCullingState.reset();
  100368. this._alphaState.reset();
  100369. }
  100370. this._cachedVertexBuffers = null;
  100371. this._cachedIndexBuffer = null;
  100372. this._cachedEffectForVertexBuffers = null;
  100373. };
  100374. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  100375. };
  100376. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  100377. };
  100378. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  100379. };
  100380. NullEngine.prototype._createTexture = function () {
  100381. return {};
  100382. };
  100383. NullEngine.prototype._releaseTexture = function (texture) {
  100384. };
  100385. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  100386. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  100387. if (onLoad === void 0) { onLoad = null; }
  100388. if (onError === void 0) { onError = null; }
  100389. if (buffer === void 0) { buffer = null; }
  100390. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  100391. var url = String(urlArg);
  100392. texture.url = url;
  100393. texture.generateMipMaps = !noMipmap;
  100394. texture.samplingMode = samplingMode;
  100395. texture.invertY = invertY;
  100396. texture.baseWidth = this._options.textureSize;
  100397. texture.baseHeight = this._options.textureSize;
  100398. texture.width = this._options.textureSize;
  100399. texture.height = this._options.textureSize;
  100400. if (format) {
  100401. texture.format = format;
  100402. }
  100403. texture.isReady = true;
  100404. if (onLoad) {
  100405. onLoad();
  100406. }
  100407. this._internalTexturesCache.push(texture);
  100408. return texture;
  100409. };
  100410. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  100411. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  100412. if (options !== undefined && typeof options === "object") {
  100413. fullOptions.generateMipMaps = options.generateMipMaps;
  100414. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  100415. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  100416. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  100417. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  100418. }
  100419. else {
  100420. fullOptions.generateMipMaps = options;
  100421. fullOptions.generateDepthBuffer = true;
  100422. fullOptions.generateStencilBuffer = false;
  100423. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100424. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  100425. }
  100426. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  100427. var width = size.width || size;
  100428. var height = size.height || size;
  100429. texture._depthStencilBuffer = {};
  100430. texture._framebuffer = {};
  100431. texture.baseWidth = width;
  100432. texture.baseHeight = height;
  100433. texture.width = width;
  100434. texture.height = height;
  100435. texture.isReady = true;
  100436. texture.samples = 1;
  100437. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  100438. texture.samplingMode = fullOptions.samplingMode;
  100439. texture.type = fullOptions.type;
  100440. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  100441. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  100442. this._internalTexturesCache.push(texture);
  100443. return texture;
  100444. };
  100445. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  100446. texture.samplingMode = samplingMode;
  100447. };
  100448. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  100449. if (this._currentRenderTarget) {
  100450. this.unBindFramebuffer(this._currentRenderTarget);
  100451. }
  100452. this._currentRenderTarget = texture;
  100453. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  100454. if (this._cachedViewport && !forceFullscreenViewport) {
  100455. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  100456. }
  100457. };
  100458. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  100459. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  100460. this._currentRenderTarget = null;
  100461. if (onBeforeUnbind) {
  100462. if (texture._MSAAFramebuffer) {
  100463. this._currentFramebuffer = texture._framebuffer;
  100464. }
  100465. onBeforeUnbind();
  100466. }
  100467. this._currentFramebuffer = null;
  100468. };
  100469. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  100470. var vbo = {
  100471. capacity: 1,
  100472. references: 1,
  100473. is32Bits: false
  100474. };
  100475. return vbo;
  100476. };
  100477. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  100478. if (premulAlpha === void 0) { premulAlpha = false; }
  100479. };
  100480. /**
  100481. * Get the current error code of the webGL context
  100482. * @returns the error code
  100483. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  100484. */
  100485. NullEngine.prototype.getError = function () {
  100486. return 0;
  100487. };
  100488. /** @hidden */
  100489. NullEngine.prototype._getUnpackAlignement = function () {
  100490. return 1;
  100491. };
  100492. /** @hidden */
  100493. NullEngine.prototype._unpackFlipY = function (value) {
  100494. };
  100495. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  100496. if (offset === void 0) { offset = 0; }
  100497. };
  100498. /**
  100499. * Updates a dynamic vertex buffer.
  100500. * @param vertexBuffer the vertex buffer to update
  100501. * @param data the data used to update the vertex buffer
  100502. * @param byteOffset the byte offset of the data (optional)
  100503. * @param byteLength the byte length of the data (optional)
  100504. */
  100505. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  100506. };
  100507. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  100508. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  100509. this._boundTexturesCache[this._activeChannel] = texture;
  100510. return true;
  100511. }
  100512. return false;
  100513. };
  100514. NullEngine.prototype._bindTexture = function (channel, texture) {
  100515. if (channel < 0) {
  100516. return;
  100517. }
  100518. this._bindTextureDirectly(0, texture);
  100519. };
  100520. NullEngine.prototype._releaseBuffer = function (buffer) {
  100521. buffer.references--;
  100522. if (buffer.references === 0) {
  100523. return true;
  100524. }
  100525. return false;
  100526. };
  100527. NullEngine.prototype.releaseEffects = function () {
  100528. };
  100529. NullEngine.prototype.displayLoadingUI = function () {
  100530. };
  100531. NullEngine.prototype.hideLoadingUI = function () {
  100532. };
  100533. /** @hidden */
  100534. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  100535. if (faceIndex === void 0) { faceIndex = 0; }
  100536. if (lod === void 0) { lod = 0; }
  100537. };
  100538. /** @hidden */
  100539. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, width, height, imageData, faceIndex, lod) {
  100540. if (faceIndex === void 0) { faceIndex = 0; }
  100541. if (lod === void 0) { lod = 0; }
  100542. };
  100543. /** @hidden */
  100544. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  100545. if (faceIndex === void 0) { faceIndex = 0; }
  100546. if (lod === void 0) { lod = 0; }
  100547. };
  100548. /** @hidden */
  100549. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  100550. if (faceIndex === void 0) { faceIndex = 0; }
  100551. if (lod === void 0) { lod = 0; }
  100552. };
  100553. return NullEngine;
  100554. }(BABYLON.Engine));
  100555. BABYLON.NullEngine = NullEngine;
  100556. })(BABYLON || (BABYLON = {}));
  100557. //# sourceMappingURL=babylon.nullEngine.js.map
  100558. var BABYLON;
  100559. (function (BABYLON) {
  100560. /**
  100561. * This class can be used to get instrumentation data from a Babylon engine
  100562. */
  100563. var EngineInstrumentation = /** @class */ (function () {
  100564. function EngineInstrumentation(engine) {
  100565. this.engine = engine;
  100566. this._captureGPUFrameTime = false;
  100567. this._gpuFrameTime = new BABYLON.PerfCounter();
  100568. this._captureShaderCompilationTime = false;
  100569. this._shaderCompilationTime = new BABYLON.PerfCounter();
  100570. // Observers
  100571. this._onBeginFrameObserver = null;
  100572. this._onEndFrameObserver = null;
  100573. this._onBeforeShaderCompilationObserver = null;
  100574. this._onAfterShaderCompilationObserver = null;
  100575. }
  100576. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  100577. // Properties
  100578. /**
  100579. * Gets the perf counter used for GPU frame time
  100580. */
  100581. get: function () {
  100582. return this._gpuFrameTime;
  100583. },
  100584. enumerable: true,
  100585. configurable: true
  100586. });
  100587. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  100588. /**
  100589. * Gets the GPU frame time capture status
  100590. */
  100591. get: function () {
  100592. return this._captureGPUFrameTime;
  100593. },
  100594. /**
  100595. * Enable or disable the GPU frame time capture
  100596. */
  100597. set: function (value) {
  100598. var _this = this;
  100599. if (value === this._captureGPUFrameTime) {
  100600. return;
  100601. }
  100602. this._captureGPUFrameTime = value;
  100603. if (value) {
  100604. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  100605. if (!_this._gpuFrameTimeToken) {
  100606. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  100607. }
  100608. });
  100609. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  100610. if (!_this._gpuFrameTimeToken) {
  100611. return;
  100612. }
  100613. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  100614. if (time > -1) {
  100615. _this._gpuFrameTimeToken = null;
  100616. _this._gpuFrameTime.fetchNewFrame();
  100617. _this._gpuFrameTime.addCount(time, true);
  100618. }
  100619. });
  100620. }
  100621. else {
  100622. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100623. this._onBeginFrameObserver = null;
  100624. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100625. this._onEndFrameObserver = null;
  100626. }
  100627. },
  100628. enumerable: true,
  100629. configurable: true
  100630. });
  100631. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  100632. /**
  100633. * Gets the perf counter used for shader compilation time
  100634. */
  100635. get: function () {
  100636. return this._shaderCompilationTime;
  100637. },
  100638. enumerable: true,
  100639. configurable: true
  100640. });
  100641. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  100642. /**
  100643. * Gets the shader compilation time capture status
  100644. */
  100645. get: function () {
  100646. return this._captureShaderCompilationTime;
  100647. },
  100648. /**
  100649. * Enable or disable the shader compilation time capture
  100650. */
  100651. set: function (value) {
  100652. var _this = this;
  100653. if (value === this._captureShaderCompilationTime) {
  100654. return;
  100655. }
  100656. this._captureShaderCompilationTime = value;
  100657. if (value) {
  100658. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  100659. _this._shaderCompilationTime.fetchNewFrame();
  100660. _this._shaderCompilationTime.beginMonitoring();
  100661. });
  100662. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  100663. _this._shaderCompilationTime.endMonitoring();
  100664. });
  100665. }
  100666. else {
  100667. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100668. this._onBeforeShaderCompilationObserver = null;
  100669. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100670. this._onAfterShaderCompilationObserver = null;
  100671. }
  100672. },
  100673. enumerable: true,
  100674. configurable: true
  100675. });
  100676. EngineInstrumentation.prototype.dispose = function () {
  100677. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100678. this._onBeginFrameObserver = null;
  100679. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100680. this._onEndFrameObserver = null;
  100681. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100682. this._onBeforeShaderCompilationObserver = null;
  100683. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100684. this._onAfterShaderCompilationObserver = null;
  100685. this.engine = null;
  100686. };
  100687. return EngineInstrumentation;
  100688. }());
  100689. BABYLON.EngineInstrumentation = EngineInstrumentation;
  100690. })(BABYLON || (BABYLON = {}));
  100691. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  100692. var BABYLON;
  100693. (function (BABYLON) {
  100694. /**
  100695. * This class can be used to get instrumentation data from a Babylon engine
  100696. */
  100697. var SceneInstrumentation = /** @class */ (function () {
  100698. function SceneInstrumentation(scene) {
  100699. var _this = this;
  100700. this.scene = scene;
  100701. this._captureActiveMeshesEvaluationTime = false;
  100702. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  100703. this._captureRenderTargetsRenderTime = false;
  100704. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  100705. this._captureFrameTime = false;
  100706. this._frameTime = new BABYLON.PerfCounter();
  100707. this._captureRenderTime = false;
  100708. this._renderTime = new BABYLON.PerfCounter();
  100709. this._captureInterFrameTime = false;
  100710. this._interFrameTime = new BABYLON.PerfCounter();
  100711. this._captureParticlesRenderTime = false;
  100712. this._particlesRenderTime = new BABYLON.PerfCounter();
  100713. this._captureSpritesRenderTime = false;
  100714. this._spritesRenderTime = new BABYLON.PerfCounter();
  100715. this._capturePhysicsTime = false;
  100716. this._physicsTime = new BABYLON.PerfCounter();
  100717. this._captureAnimationsTime = false;
  100718. this._animationsTime = new BABYLON.PerfCounter();
  100719. this._captureCameraRenderTime = false;
  100720. this._cameraRenderTime = new BABYLON.PerfCounter();
  100721. // Observers
  100722. this._onBeforeActiveMeshesEvaluationObserver = null;
  100723. this._onAfterActiveMeshesEvaluationObserver = null;
  100724. this._onBeforeRenderTargetsRenderObserver = null;
  100725. this._onAfterRenderTargetsRenderObserver = null;
  100726. this._onAfterRenderObserver = null;
  100727. this._onBeforeDrawPhaseObserver = null;
  100728. this._onAfterDrawPhaseObserver = null;
  100729. this._onBeforeAnimationsObserver = null;
  100730. this._onBeforeParticlesRenderingObserver = null;
  100731. this._onAfterParticlesRenderingObserver = null;
  100732. this._onBeforeSpritesRenderingObserver = null;
  100733. this._onAfterSpritesRenderingObserver = null;
  100734. this._onBeforePhysicsObserver = null;
  100735. this._onAfterPhysicsObserver = null;
  100736. this._onAfterAnimationsObserver = null;
  100737. this._onBeforeCameraRenderObserver = null;
  100738. this._onAfterCameraRenderObserver = null;
  100739. // Before render
  100740. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  100741. if (_this._captureActiveMeshesEvaluationTime) {
  100742. _this._activeMeshesEvaluationTime.fetchNewFrame();
  100743. }
  100744. if (_this._captureRenderTargetsRenderTime) {
  100745. _this._renderTargetsRenderTime.fetchNewFrame();
  100746. }
  100747. if (_this._captureFrameTime) {
  100748. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  100749. _this._frameTime.beginMonitoring();
  100750. }
  100751. if (_this._captureInterFrameTime) {
  100752. _this._interFrameTime.endMonitoring();
  100753. }
  100754. if (_this._captureParticlesRenderTime) {
  100755. _this._particlesRenderTime.fetchNewFrame();
  100756. }
  100757. if (_this._captureSpritesRenderTime) {
  100758. _this._spritesRenderTime.fetchNewFrame();
  100759. }
  100760. if (_this._captureAnimationsTime) {
  100761. _this._animationsTime.beginMonitoring();
  100762. }
  100763. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  100764. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  100765. });
  100766. // After render
  100767. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  100768. if (_this._captureFrameTime) {
  100769. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  100770. _this._frameTime.endMonitoring();
  100771. }
  100772. if (_this._captureRenderTime) {
  100773. _this._renderTime.endMonitoring(false);
  100774. }
  100775. if (_this._captureInterFrameTime) {
  100776. _this._interFrameTime.beginMonitoring();
  100777. }
  100778. });
  100779. }
  100780. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  100781. // Properties
  100782. /**
  100783. * Gets the perf counter used for active meshes evaluation time
  100784. */
  100785. get: function () {
  100786. return this._activeMeshesEvaluationTime;
  100787. },
  100788. enumerable: true,
  100789. configurable: true
  100790. });
  100791. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  100792. /**
  100793. * Gets the active meshes evaluation time capture status
  100794. */
  100795. get: function () {
  100796. return this._captureActiveMeshesEvaluationTime;
  100797. },
  100798. /**
  100799. * Enable or disable the active meshes evaluation time capture
  100800. */
  100801. set: function (value) {
  100802. var _this = this;
  100803. if (value === this._captureActiveMeshesEvaluationTime) {
  100804. return;
  100805. }
  100806. this._captureActiveMeshesEvaluationTime = value;
  100807. if (value) {
  100808. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  100809. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  100810. _this._activeMeshesEvaluationTime.beginMonitoring();
  100811. });
  100812. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  100813. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  100814. _this._activeMeshesEvaluationTime.endMonitoring();
  100815. });
  100816. }
  100817. else {
  100818. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  100819. this._onBeforeActiveMeshesEvaluationObserver = null;
  100820. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  100821. this._onAfterActiveMeshesEvaluationObserver = null;
  100822. }
  100823. },
  100824. enumerable: true,
  100825. configurable: true
  100826. });
  100827. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  100828. /**
  100829. * Gets the perf counter used for render targets render time
  100830. */
  100831. get: function () {
  100832. return this._renderTargetsRenderTime;
  100833. },
  100834. enumerable: true,
  100835. configurable: true
  100836. });
  100837. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  100838. /**
  100839. * Gets the render targets render time capture status
  100840. */
  100841. get: function () {
  100842. return this._captureRenderTargetsRenderTime;
  100843. },
  100844. /**
  100845. * Enable or disable the render targets render time capture
  100846. */
  100847. set: function (value) {
  100848. var _this = this;
  100849. if (value === this._captureRenderTargetsRenderTime) {
  100850. return;
  100851. }
  100852. this._captureRenderTargetsRenderTime = value;
  100853. if (value) {
  100854. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  100855. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  100856. _this._renderTargetsRenderTime.beginMonitoring();
  100857. });
  100858. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  100859. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  100860. _this._renderTargetsRenderTime.endMonitoring(false);
  100861. });
  100862. }
  100863. else {
  100864. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  100865. this._onBeforeRenderTargetsRenderObserver = null;
  100866. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  100867. this._onAfterRenderTargetsRenderObserver = null;
  100868. }
  100869. },
  100870. enumerable: true,
  100871. configurable: true
  100872. });
  100873. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  100874. /**
  100875. * Gets the perf counter used for particles render time
  100876. */
  100877. get: function () {
  100878. return this._particlesRenderTime;
  100879. },
  100880. enumerable: true,
  100881. configurable: true
  100882. });
  100883. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  100884. /**
  100885. * Gets the particles render time capture status
  100886. */
  100887. get: function () {
  100888. return this._captureParticlesRenderTime;
  100889. },
  100890. /**
  100891. * Enable or disable the particles render time capture
  100892. */
  100893. set: function (value) {
  100894. var _this = this;
  100895. if (value === this._captureParticlesRenderTime) {
  100896. return;
  100897. }
  100898. this._captureParticlesRenderTime = value;
  100899. if (value) {
  100900. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  100901. BABYLON.Tools.StartPerformanceCounter("Particles");
  100902. _this._particlesRenderTime.beginMonitoring();
  100903. });
  100904. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  100905. BABYLON.Tools.EndPerformanceCounter("Particles");
  100906. _this._particlesRenderTime.endMonitoring(false);
  100907. });
  100908. }
  100909. else {
  100910. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  100911. this._onBeforeParticlesRenderingObserver = null;
  100912. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  100913. this._onAfterParticlesRenderingObserver = null;
  100914. }
  100915. },
  100916. enumerable: true,
  100917. configurable: true
  100918. });
  100919. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  100920. /**
  100921. * Gets the perf counter used for sprites render time
  100922. */
  100923. get: function () {
  100924. return this._spritesRenderTime;
  100925. },
  100926. enumerable: true,
  100927. configurable: true
  100928. });
  100929. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  100930. /**
  100931. * Gets the sprites render time capture status
  100932. */
  100933. get: function () {
  100934. return this._captureSpritesRenderTime;
  100935. },
  100936. /**
  100937. * Enable or disable the sprites render time capture
  100938. */
  100939. set: function (value) {
  100940. var _this = this;
  100941. if (value === this._captureSpritesRenderTime) {
  100942. return;
  100943. }
  100944. this._captureSpritesRenderTime = value;
  100945. if (value) {
  100946. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  100947. BABYLON.Tools.StartPerformanceCounter("Sprites");
  100948. _this._spritesRenderTime.beginMonitoring();
  100949. });
  100950. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  100951. BABYLON.Tools.EndPerformanceCounter("Sprites");
  100952. _this._spritesRenderTime.endMonitoring(false);
  100953. });
  100954. }
  100955. else {
  100956. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  100957. this._onBeforeSpritesRenderingObserver = null;
  100958. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  100959. this._onAfterSpritesRenderingObserver = null;
  100960. }
  100961. },
  100962. enumerable: true,
  100963. configurable: true
  100964. });
  100965. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  100966. /**
  100967. * Gets the perf counter used for physics time
  100968. */
  100969. get: function () {
  100970. return this._physicsTime;
  100971. },
  100972. enumerable: true,
  100973. configurable: true
  100974. });
  100975. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  100976. /**
  100977. * Gets the physics time capture status
  100978. */
  100979. get: function () {
  100980. return this._capturePhysicsTime;
  100981. },
  100982. /**
  100983. * Enable or disable the physics time capture
  100984. */
  100985. set: function (value) {
  100986. var _this = this;
  100987. if (value === this._capturePhysicsTime) {
  100988. return;
  100989. }
  100990. this._capturePhysicsTime = value;
  100991. if (value) {
  100992. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  100993. BABYLON.Tools.StartPerformanceCounter("Physics");
  100994. _this._physicsTime.beginMonitoring();
  100995. });
  100996. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  100997. BABYLON.Tools.EndPerformanceCounter("Physics");
  100998. _this._physicsTime.endMonitoring();
  100999. });
  101000. }
  101001. else {
  101002. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101003. this._onBeforePhysicsObserver = null;
  101004. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101005. this._onAfterPhysicsObserver = null;
  101006. }
  101007. },
  101008. enumerable: true,
  101009. configurable: true
  101010. });
  101011. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  101012. /**
  101013. * Gets the perf counter used for animations time
  101014. */
  101015. get: function () {
  101016. return this._animationsTime;
  101017. },
  101018. enumerable: true,
  101019. configurable: true
  101020. });
  101021. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  101022. /**
  101023. * Gets the animations time capture status
  101024. */
  101025. get: function () {
  101026. return this._captureAnimationsTime;
  101027. },
  101028. /**
  101029. * Enable or disable the animations time capture
  101030. */
  101031. set: function (value) {
  101032. var _this = this;
  101033. if (value === this._captureAnimationsTime) {
  101034. return;
  101035. }
  101036. this._captureAnimationsTime = value;
  101037. if (value) {
  101038. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  101039. _this._animationsTime.endMonitoring();
  101040. });
  101041. }
  101042. else {
  101043. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101044. this._onAfterAnimationsObserver = null;
  101045. }
  101046. },
  101047. enumerable: true,
  101048. configurable: true
  101049. });
  101050. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  101051. /**
  101052. * Gets the perf counter used for frame time capture
  101053. */
  101054. get: function () {
  101055. return this._frameTime;
  101056. },
  101057. enumerable: true,
  101058. configurable: true
  101059. });
  101060. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  101061. /**
  101062. * Gets the frame time capture status
  101063. */
  101064. get: function () {
  101065. return this._captureFrameTime;
  101066. },
  101067. /**
  101068. * Enable or disable the frame time capture
  101069. */
  101070. set: function (value) {
  101071. this._captureFrameTime = value;
  101072. },
  101073. enumerable: true,
  101074. configurable: true
  101075. });
  101076. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  101077. /**
  101078. * Gets the perf counter used for inter-frames time capture
  101079. */
  101080. get: function () {
  101081. return this._interFrameTime;
  101082. },
  101083. enumerable: true,
  101084. configurable: true
  101085. });
  101086. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  101087. /**
  101088. * Gets the inter-frames time capture status
  101089. */
  101090. get: function () {
  101091. return this._captureInterFrameTime;
  101092. },
  101093. /**
  101094. * Enable or disable the inter-frames time capture
  101095. */
  101096. set: function (value) {
  101097. this._captureInterFrameTime = value;
  101098. },
  101099. enumerable: true,
  101100. configurable: true
  101101. });
  101102. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  101103. /**
  101104. * Gets the perf counter used for render time capture
  101105. */
  101106. get: function () {
  101107. return this._renderTime;
  101108. },
  101109. enumerable: true,
  101110. configurable: true
  101111. });
  101112. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  101113. /**
  101114. * Gets the render time capture status
  101115. */
  101116. get: function () {
  101117. return this._captureRenderTime;
  101118. },
  101119. /**
  101120. * Enable or disable the render time capture
  101121. */
  101122. set: function (value) {
  101123. var _this = this;
  101124. if (value === this._captureRenderTime) {
  101125. return;
  101126. }
  101127. this._captureRenderTime = value;
  101128. if (value) {
  101129. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  101130. _this._renderTime.beginMonitoring();
  101131. BABYLON.Tools.StartPerformanceCounter("Main render");
  101132. });
  101133. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  101134. _this._renderTime.endMonitoring(false);
  101135. BABYLON.Tools.EndPerformanceCounter("Main render");
  101136. });
  101137. }
  101138. else {
  101139. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  101140. this._onBeforeDrawPhaseObserver = null;
  101141. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  101142. this._onAfterDrawPhaseObserver = null;
  101143. }
  101144. },
  101145. enumerable: true,
  101146. configurable: true
  101147. });
  101148. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  101149. /**
  101150. * Gets the perf counter used for camera render time capture
  101151. */
  101152. get: function () {
  101153. return this._cameraRenderTime;
  101154. },
  101155. enumerable: true,
  101156. configurable: true
  101157. });
  101158. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  101159. /**
  101160. * Gets the camera render time capture status
  101161. */
  101162. get: function () {
  101163. return this._captureCameraRenderTime;
  101164. },
  101165. /**
  101166. * Enable or disable the camera render time capture
  101167. */
  101168. set: function (value) {
  101169. var _this = this;
  101170. if (value === this._captureCameraRenderTime) {
  101171. return;
  101172. }
  101173. this._captureCameraRenderTime = value;
  101174. if (value) {
  101175. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  101176. _this._cameraRenderTime.beginMonitoring();
  101177. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  101178. });
  101179. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  101180. _this._cameraRenderTime.endMonitoring(false);
  101181. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  101182. });
  101183. }
  101184. else {
  101185. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101186. this._onBeforeCameraRenderObserver = null;
  101187. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101188. this._onAfterCameraRenderObserver = null;
  101189. }
  101190. },
  101191. enumerable: true,
  101192. configurable: true
  101193. });
  101194. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  101195. /**
  101196. * Gets the perf counter used for draw calls
  101197. */
  101198. get: function () {
  101199. return this.scene.getEngine()._drawCalls;
  101200. },
  101201. enumerable: true,
  101202. configurable: true
  101203. });
  101204. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  101205. /**
  101206. * Gets the perf counter used for texture collisions
  101207. */
  101208. get: function () {
  101209. return this.scene.getEngine()._textureCollisions;
  101210. },
  101211. enumerable: true,
  101212. configurable: true
  101213. });
  101214. SceneInstrumentation.prototype.dispose = function () {
  101215. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  101216. this._onAfterRenderObserver = null;
  101217. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  101218. this._onBeforeActiveMeshesEvaluationObserver = null;
  101219. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  101220. this._onAfterActiveMeshesEvaluationObserver = null;
  101221. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  101222. this._onBeforeRenderTargetsRenderObserver = null;
  101223. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  101224. this._onAfterRenderTargetsRenderObserver = null;
  101225. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  101226. this._onBeforeAnimationsObserver = null;
  101227. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101228. this._onBeforeParticlesRenderingObserver = null;
  101229. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101230. this._onAfterParticlesRenderingObserver = null;
  101231. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101232. this._onBeforeSpritesRenderingObserver = null;
  101233. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101234. this._onAfterSpritesRenderingObserver = null;
  101235. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  101236. this._onBeforeDrawPhaseObserver = null;
  101237. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  101238. this._onAfterDrawPhaseObserver = null;
  101239. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101240. this._onBeforePhysicsObserver = null;
  101241. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101242. this._onAfterPhysicsObserver = null;
  101243. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101244. this._onAfterAnimationsObserver = null;
  101245. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101246. this._onBeforeCameraRenderObserver = null;
  101247. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101248. this._onAfterCameraRenderObserver = null;
  101249. this.scene = null;
  101250. };
  101251. return SceneInstrumentation;
  101252. }());
  101253. BABYLON.SceneInstrumentation = SceneInstrumentation;
  101254. })(BABYLON || (BABYLON = {}));
  101255. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  101256. var BABYLON;
  101257. (function (BABYLON) {
  101258. /**
  101259. * @hidden
  101260. **/
  101261. var _TimeToken = /** @class */ (function () {
  101262. function _TimeToken() {
  101263. this._timeElapsedQueryEnded = false;
  101264. }
  101265. return _TimeToken;
  101266. }());
  101267. BABYLON._TimeToken = _TimeToken;
  101268. })(BABYLON || (BABYLON = {}));
  101269. //# sourceMappingURL=babylon.timeToken.js.map
  101270. var BABYLON;
  101271. (function (BABYLON) {
  101272. /**
  101273. * Background material defines definition.
  101274. * @hidden Mainly internal Use
  101275. */
  101276. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  101277. __extends(BackgroundMaterialDefines, _super);
  101278. /**
  101279. * Constructor of the defines.
  101280. */
  101281. function BackgroundMaterialDefines() {
  101282. var _this = _super.call(this) || this;
  101283. /**
  101284. * True if the diffuse texture is in use.
  101285. */
  101286. _this.DIFFUSE = false;
  101287. /**
  101288. * The direct UV channel to use.
  101289. */
  101290. _this.DIFFUSEDIRECTUV = 0;
  101291. /**
  101292. * True if the diffuse texture is in gamma space.
  101293. */
  101294. _this.GAMMADIFFUSE = false;
  101295. /**
  101296. * True if the diffuse texture has opacity in the alpha channel.
  101297. */
  101298. _this.DIFFUSEHASALPHA = false;
  101299. /**
  101300. * True if you want the material to fade to transparent at grazing angle.
  101301. */
  101302. _this.OPACITYFRESNEL = false;
  101303. /**
  101304. * True if an extra blur needs to be added in the reflection.
  101305. */
  101306. _this.REFLECTIONBLUR = false;
  101307. /**
  101308. * True if you want the material to fade to reflection at grazing angle.
  101309. */
  101310. _this.REFLECTIONFRESNEL = false;
  101311. /**
  101312. * True if you want the material to falloff as far as you move away from the scene center.
  101313. */
  101314. _this.REFLECTIONFALLOFF = false;
  101315. /**
  101316. * False if the current Webgl implementation does not support the texture lod extension.
  101317. */
  101318. _this.TEXTURELODSUPPORT = false;
  101319. /**
  101320. * True to ensure the data are premultiplied.
  101321. */
  101322. _this.PREMULTIPLYALPHA = false;
  101323. /**
  101324. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  101325. */
  101326. _this.USERGBCOLOR = false;
  101327. /**
  101328. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  101329. * stays aligned with the desired configuration.
  101330. */
  101331. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  101332. /**
  101333. * True to add noise in order to reduce the banding effect.
  101334. */
  101335. _this.NOISE = false;
  101336. /**
  101337. * is the reflection texture in BGR color scheme?
  101338. * Mainly used to solve a bug in ios10 video tag
  101339. */
  101340. _this.REFLECTIONBGR = false;
  101341. _this.IMAGEPROCESSING = false;
  101342. _this.VIGNETTE = false;
  101343. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  101344. _this.VIGNETTEBLENDMODEOPAQUE = false;
  101345. _this.TONEMAPPING = false;
  101346. _this.CONTRAST = false;
  101347. _this.COLORCURVES = false;
  101348. _this.COLORGRADING = false;
  101349. _this.COLORGRADING3D = false;
  101350. _this.SAMPLER3DGREENDEPTH = false;
  101351. _this.SAMPLER3DBGRMAP = false;
  101352. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  101353. _this.EXPOSURE = false;
  101354. // Reflection.
  101355. _this.REFLECTION = false;
  101356. _this.REFLECTIONMAP_3D = false;
  101357. _this.REFLECTIONMAP_SPHERICAL = false;
  101358. _this.REFLECTIONMAP_PLANAR = false;
  101359. _this.REFLECTIONMAP_CUBIC = false;
  101360. _this.REFLECTIONMAP_PROJECTION = false;
  101361. _this.REFLECTIONMAP_SKYBOX = false;
  101362. _this.REFLECTIONMAP_EXPLICIT = false;
  101363. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  101364. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  101365. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  101366. _this.INVERTCUBICMAP = false;
  101367. _this.REFLECTIONMAP_OPPOSITEZ = false;
  101368. _this.LODINREFLECTIONALPHA = false;
  101369. _this.GAMMAREFLECTION = false;
  101370. _this.RGBDREFLECTION = false;
  101371. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  101372. // Default BJS.
  101373. _this.MAINUV1 = false;
  101374. _this.MAINUV2 = false;
  101375. _this.UV1 = false;
  101376. _this.UV2 = false;
  101377. _this.CLIPPLANE = false;
  101378. _this.POINTSIZE = false;
  101379. _this.FOG = false;
  101380. _this.NORMAL = false;
  101381. _this.NUM_BONE_INFLUENCERS = 0;
  101382. _this.BonesPerMesh = 0;
  101383. _this.INSTANCES = false;
  101384. _this.SHADOWFLOAT = false;
  101385. _this.rebuild();
  101386. return _this;
  101387. }
  101388. return BackgroundMaterialDefines;
  101389. }(BABYLON.MaterialDefines));
  101390. /**
  101391. * Background material used to create an efficient environement around your scene.
  101392. */
  101393. var BackgroundMaterial = /** @class */ (function (_super) {
  101394. __extends(BackgroundMaterial, _super);
  101395. /**
  101396. * Instantiates a Background Material in the given scene
  101397. * @param name The friendly name of the material
  101398. * @param scene The scene to add the material to
  101399. */
  101400. function BackgroundMaterial(name, scene) {
  101401. var _this = _super.call(this, name, scene) || this;
  101402. /**
  101403. * Key light Color (multiply against the environement texture)
  101404. */
  101405. _this.primaryColor = BABYLON.Color3.White();
  101406. _this._primaryColorShadowLevel = 0;
  101407. _this._primaryColorHighlightLevel = 0;
  101408. /**
  101409. * Reflection Texture used in the material.
  101410. * Should be author in a specific way for the best result (refer to the documentation).
  101411. */
  101412. _this.reflectionTexture = null;
  101413. /**
  101414. * Reflection Texture level of blur.
  101415. *
  101416. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  101417. * texture twice.
  101418. */
  101419. _this.reflectionBlur = 0;
  101420. /**
  101421. * Diffuse Texture used in the material.
  101422. * Should be author in a specific way for the best result (refer to the documentation).
  101423. */
  101424. _this.diffuseTexture = null;
  101425. _this._shadowLights = null;
  101426. /**
  101427. * Specify the list of lights casting shadow on the material.
  101428. * All scene shadow lights will be included if null.
  101429. */
  101430. _this.shadowLights = null;
  101431. /**
  101432. * Helps adjusting the shadow to a softer level if required.
  101433. * 0 means black shadows and 1 means no shadows.
  101434. */
  101435. _this.shadowLevel = 0;
  101436. /**
  101437. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  101438. * It is usually zero but might be interesting to modify according to your setup.
  101439. */
  101440. _this.sceneCenter = BABYLON.Vector3.Zero();
  101441. /**
  101442. * This helps specifying that the material is falling off to the sky box at grazing angle.
  101443. * This helps ensuring a nice transition when the camera goes under the ground.
  101444. */
  101445. _this.opacityFresnel = true;
  101446. /**
  101447. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  101448. * This helps adding a mirror texture on the ground.
  101449. */
  101450. _this.reflectionFresnel = false;
  101451. /**
  101452. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  101453. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  101454. */
  101455. _this.reflectionFalloffDistance = 0.0;
  101456. /**
  101457. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  101458. */
  101459. _this.reflectionAmount = 1.0;
  101460. /**
  101461. * This specifies the weight of the reflection at grazing angle.
  101462. */
  101463. _this.reflectionReflectance0 = 0.05;
  101464. /**
  101465. * This specifies the weight of the reflection at a perpendicular point of view.
  101466. */
  101467. _this.reflectionReflectance90 = 0.5;
  101468. /**
  101469. * Helps to directly use the maps channels instead of their level.
  101470. */
  101471. _this.useRGBColor = true;
  101472. /**
  101473. * This helps reducing the banding effect that could occur on the background.
  101474. */
  101475. _this.enableNoise = false;
  101476. _this._fovMultiplier = 1.0;
  101477. /**
  101478. * Enable the FOV adjustment feature controlled by fovMultiplier.
  101479. */
  101480. _this.useEquirectangularFOV = false;
  101481. _this._maxSimultaneousLights = 4;
  101482. /**
  101483. * Number of Simultaneous lights allowed on the material.
  101484. */
  101485. _this.maxSimultaneousLights = 4;
  101486. /**
  101487. * Keep track of the image processing observer to allow dispose and replace.
  101488. */
  101489. _this._imageProcessingObserver = null;
  101490. /**
  101491. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  101492. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  101493. */
  101494. _this.switchToBGR = false;
  101495. // Temp values kept as cache in the material.
  101496. _this._renderTargets = new BABYLON.SmartArray(16);
  101497. _this._reflectionControls = BABYLON.Vector4.Zero();
  101498. _this._white = BABYLON.Color3.White();
  101499. _this._primaryShadowColor = BABYLON.Color3.Black();
  101500. _this._primaryHighlightColor = BABYLON.Color3.Black();
  101501. // Setup the default processing configuration to the scene.
  101502. _this._attachImageProcessingConfiguration(null);
  101503. _this.getRenderTargetTextures = function () {
  101504. _this._renderTargets.reset();
  101505. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  101506. _this._renderTargets.push(_this._diffuseTexture);
  101507. }
  101508. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  101509. _this._renderTargets.push(_this._reflectionTexture);
  101510. }
  101511. return _this._renderTargets;
  101512. };
  101513. return _this;
  101514. }
  101515. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  101516. /**
  101517. * Experimental Internal Use Only.
  101518. *
  101519. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  101520. * This acts as a helper to set the primary color to a more "human friendly" value.
  101521. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  101522. * output color as close as possible from the chosen value.
  101523. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  101524. * part of lighting setup.)
  101525. */
  101526. get: function () {
  101527. return this.__perceptualColor;
  101528. },
  101529. set: function (value) {
  101530. this.__perceptualColor = value;
  101531. this._computePrimaryColorFromPerceptualColor();
  101532. this._markAllSubMeshesAsLightsDirty();
  101533. },
  101534. enumerable: true,
  101535. configurable: true
  101536. });
  101537. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  101538. /**
  101539. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  101540. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  101541. */
  101542. get: function () {
  101543. return this._primaryColorShadowLevel;
  101544. },
  101545. set: function (value) {
  101546. this._primaryColorShadowLevel = value;
  101547. this._computePrimaryColors();
  101548. this._markAllSubMeshesAsLightsDirty();
  101549. },
  101550. enumerable: true,
  101551. configurable: true
  101552. });
  101553. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  101554. /**
  101555. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  101556. * The primary color is used at the level chosen to define what the white area would look.
  101557. */
  101558. get: function () {
  101559. return this._primaryColorHighlightLevel;
  101560. },
  101561. set: function (value) {
  101562. this._primaryColorHighlightLevel = value;
  101563. this._computePrimaryColors();
  101564. this._markAllSubMeshesAsLightsDirty();
  101565. },
  101566. enumerable: true,
  101567. configurable: true
  101568. });
  101569. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  101570. /**
  101571. * Sets the reflection reflectance fresnel values according to the default standard
  101572. * empirically know to work well :-)
  101573. */
  101574. set: function (value) {
  101575. var reflectionWeight = value;
  101576. if (reflectionWeight < 0.5) {
  101577. reflectionWeight = reflectionWeight * 2.0;
  101578. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  101579. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  101580. }
  101581. else {
  101582. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  101583. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  101584. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  101585. }
  101586. },
  101587. enumerable: true,
  101588. configurable: true
  101589. });
  101590. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  101591. /**
  101592. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101593. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  101594. * Recommended to be keep at 1.0 except for special cases.
  101595. */
  101596. get: function () {
  101597. return this._fovMultiplier;
  101598. },
  101599. set: function (value) {
  101600. if (isNaN(value)) {
  101601. value = 1.0;
  101602. }
  101603. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  101604. },
  101605. enumerable: true,
  101606. configurable: true
  101607. });
  101608. /**
  101609. * Attaches a new image processing configuration to the PBR Material.
  101610. * @param configuration (if null the scene configuration will be use)
  101611. */
  101612. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  101613. var _this = this;
  101614. if (configuration === this._imageProcessingConfiguration) {
  101615. return;
  101616. }
  101617. // Detaches observer.
  101618. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  101619. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  101620. }
  101621. // Pick the scene configuration if needed.
  101622. if (!configuration) {
  101623. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  101624. }
  101625. else {
  101626. this._imageProcessingConfiguration = configuration;
  101627. }
  101628. // Attaches observer.
  101629. if (this._imageProcessingConfiguration) {
  101630. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  101631. _this._computePrimaryColorFromPerceptualColor();
  101632. _this._markAllSubMeshesAsImageProcessingDirty();
  101633. });
  101634. }
  101635. };
  101636. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  101637. /**
  101638. * Gets the image processing configuration used either in this material.
  101639. */
  101640. get: function () {
  101641. return this._imageProcessingConfiguration;
  101642. },
  101643. /**
  101644. * Sets the Default image processing configuration used either in the this material.
  101645. *
  101646. * If sets to null, the scene one is in use.
  101647. */
  101648. set: function (value) {
  101649. this._attachImageProcessingConfiguration(value);
  101650. // Ensure the effect will be rebuilt.
  101651. this._markAllSubMeshesAsTexturesDirty();
  101652. },
  101653. enumerable: true,
  101654. configurable: true
  101655. });
  101656. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  101657. /**
  101658. * Gets wether the color curves effect is enabled.
  101659. */
  101660. get: function () {
  101661. return this.imageProcessingConfiguration.colorCurvesEnabled;
  101662. },
  101663. /**
  101664. * Sets wether the color curves effect is enabled.
  101665. */
  101666. set: function (value) {
  101667. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  101668. },
  101669. enumerable: true,
  101670. configurable: true
  101671. });
  101672. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  101673. /**
  101674. * Gets wether the color grading effect is enabled.
  101675. */
  101676. get: function () {
  101677. return this.imageProcessingConfiguration.colorGradingEnabled;
  101678. },
  101679. /**
  101680. * Gets wether the color grading effect is enabled.
  101681. */
  101682. set: function (value) {
  101683. this.imageProcessingConfiguration.colorGradingEnabled = value;
  101684. },
  101685. enumerable: true,
  101686. configurable: true
  101687. });
  101688. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  101689. /**
  101690. * Gets wether tonemapping is enabled or not.
  101691. */
  101692. get: function () {
  101693. return this._imageProcessingConfiguration.toneMappingEnabled;
  101694. },
  101695. /**
  101696. * Sets wether tonemapping is enabled or not
  101697. */
  101698. set: function (value) {
  101699. this._imageProcessingConfiguration.toneMappingEnabled = value;
  101700. },
  101701. enumerable: true,
  101702. configurable: true
  101703. });
  101704. ;
  101705. ;
  101706. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  101707. /**
  101708. * The camera exposure used on this material.
  101709. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101710. * This corresponds to a photographic exposure.
  101711. */
  101712. get: function () {
  101713. return this._imageProcessingConfiguration.exposure;
  101714. },
  101715. /**
  101716. * The camera exposure used on this material.
  101717. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101718. * This corresponds to a photographic exposure.
  101719. */
  101720. set: function (value) {
  101721. this._imageProcessingConfiguration.exposure = value;
  101722. },
  101723. enumerable: true,
  101724. configurable: true
  101725. });
  101726. ;
  101727. ;
  101728. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  101729. /**
  101730. * Gets The camera contrast used on this material.
  101731. */
  101732. get: function () {
  101733. return this._imageProcessingConfiguration.contrast;
  101734. },
  101735. /**
  101736. * Sets The camera contrast used on this material.
  101737. */
  101738. set: function (value) {
  101739. this._imageProcessingConfiguration.contrast = value;
  101740. },
  101741. enumerable: true,
  101742. configurable: true
  101743. });
  101744. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  101745. /**
  101746. * Gets the Color Grading 2D Lookup Texture.
  101747. */
  101748. get: function () {
  101749. return this._imageProcessingConfiguration.colorGradingTexture;
  101750. },
  101751. /**
  101752. * Sets the Color Grading 2D Lookup Texture.
  101753. */
  101754. set: function (value) {
  101755. this.imageProcessingConfiguration.colorGradingTexture = value;
  101756. },
  101757. enumerable: true,
  101758. configurable: true
  101759. });
  101760. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  101761. /**
  101762. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  101763. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  101764. * 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;
  101765. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  101766. */
  101767. get: function () {
  101768. return this.imageProcessingConfiguration.colorCurves;
  101769. },
  101770. /**
  101771. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  101772. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  101773. * 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;
  101774. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  101775. */
  101776. set: function (value) {
  101777. this.imageProcessingConfiguration.colorCurves = value;
  101778. },
  101779. enumerable: true,
  101780. configurable: true
  101781. });
  101782. /**
  101783. * The entire material has been created in order to prevent overdraw.
  101784. * @returns false
  101785. */
  101786. BackgroundMaterial.prototype.needAlphaTesting = function () {
  101787. return true;
  101788. };
  101789. /**
  101790. * The entire material has been created in order to prevent overdraw.
  101791. * @returns true if blending is enable
  101792. */
  101793. BackgroundMaterial.prototype.needAlphaBlending = function () {
  101794. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  101795. };
  101796. /**
  101797. * Checks wether the material is ready to be rendered for a given mesh.
  101798. * @param mesh The mesh to render
  101799. * @param subMesh The submesh to check against
  101800. * @param useInstances Specify wether or not the material is used with instances
  101801. * @returns true if all the dependencies are ready (Textures, Effects...)
  101802. */
  101803. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  101804. var _this = this;
  101805. if (useInstances === void 0) { useInstances = false; }
  101806. if (subMesh.effect && this.isFrozen) {
  101807. if (this._wasPreviouslyReady) {
  101808. return true;
  101809. }
  101810. }
  101811. if (!subMesh._materialDefines) {
  101812. subMesh._materialDefines = new BackgroundMaterialDefines();
  101813. }
  101814. var scene = this.getScene();
  101815. var defines = subMesh._materialDefines;
  101816. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  101817. if (defines._renderId === scene.getRenderId()) {
  101818. return true;
  101819. }
  101820. }
  101821. var engine = scene.getEngine();
  101822. // Lights
  101823. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  101824. defines._needNormals = true;
  101825. // Textures
  101826. if (defines._areTexturesDirty) {
  101827. defines._needUVs = false;
  101828. if (scene.texturesEnabled) {
  101829. if (scene.getEngine().getCaps().textureLOD) {
  101830. defines.TEXTURELODSUPPORT = true;
  101831. }
  101832. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101833. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  101834. return false;
  101835. }
  101836. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  101837. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  101838. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  101839. defines.OPACITYFRESNEL = this._opacityFresnel;
  101840. }
  101841. else {
  101842. defines.DIFFUSE = false;
  101843. defines.DIFFUSEHASALPHA = false;
  101844. defines.GAMMADIFFUSE = false;
  101845. defines.OPACITYFRESNEL = false;
  101846. }
  101847. var reflectionTexture = this._reflectionTexture;
  101848. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101849. if (!reflectionTexture.isReadyOrNotBlocking()) {
  101850. return false;
  101851. }
  101852. defines.REFLECTION = true;
  101853. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  101854. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  101855. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  101856. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  101857. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  101858. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  101859. defines.REFLECTIONBGR = this.switchToBGR;
  101860. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  101861. defines.INVERTCUBICMAP = true;
  101862. }
  101863. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  101864. switch (reflectionTexture.coordinatesMode) {
  101865. case BABYLON.Texture.EXPLICIT_MODE:
  101866. defines.REFLECTIONMAP_EXPLICIT = true;
  101867. break;
  101868. case BABYLON.Texture.PLANAR_MODE:
  101869. defines.REFLECTIONMAP_PLANAR = true;
  101870. break;
  101871. case BABYLON.Texture.PROJECTION_MODE:
  101872. defines.REFLECTIONMAP_PROJECTION = true;
  101873. break;
  101874. case BABYLON.Texture.SKYBOX_MODE:
  101875. defines.REFLECTIONMAP_SKYBOX = true;
  101876. break;
  101877. case BABYLON.Texture.SPHERICAL_MODE:
  101878. defines.REFLECTIONMAP_SPHERICAL = true;
  101879. break;
  101880. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  101881. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  101882. break;
  101883. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  101884. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  101885. break;
  101886. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  101887. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  101888. break;
  101889. case BABYLON.Texture.CUBIC_MODE:
  101890. case BABYLON.Texture.INVCUBIC_MODE:
  101891. default:
  101892. defines.REFLECTIONMAP_CUBIC = true;
  101893. break;
  101894. }
  101895. if (this.reflectionFresnel) {
  101896. defines.REFLECTIONFRESNEL = true;
  101897. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  101898. this._reflectionControls.x = this.reflectionAmount;
  101899. this._reflectionControls.y = this.reflectionReflectance0;
  101900. this._reflectionControls.z = this.reflectionReflectance90;
  101901. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  101902. }
  101903. else {
  101904. defines.REFLECTIONFRESNEL = false;
  101905. defines.REFLECTIONFALLOFF = false;
  101906. }
  101907. }
  101908. else {
  101909. defines.REFLECTION = false;
  101910. defines.REFLECTIONFRESNEL = false;
  101911. defines.REFLECTIONFALLOFF = false;
  101912. defines.REFLECTIONBLUR = false;
  101913. defines.REFLECTIONMAP_3D = false;
  101914. defines.REFLECTIONMAP_SPHERICAL = false;
  101915. defines.REFLECTIONMAP_PLANAR = false;
  101916. defines.REFLECTIONMAP_CUBIC = false;
  101917. defines.REFLECTIONMAP_PROJECTION = false;
  101918. defines.REFLECTIONMAP_SKYBOX = false;
  101919. defines.REFLECTIONMAP_EXPLICIT = false;
  101920. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  101921. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  101922. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  101923. defines.INVERTCUBICMAP = false;
  101924. defines.REFLECTIONMAP_OPPOSITEZ = false;
  101925. defines.LODINREFLECTIONALPHA = false;
  101926. defines.GAMMAREFLECTION = false;
  101927. defines.RGBDREFLECTION = false;
  101928. }
  101929. }
  101930. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  101931. defines.USERGBCOLOR = this._useRGBColor;
  101932. defines.NOISE = this._enableNoise;
  101933. }
  101934. if (defines._areLightsDirty) {
  101935. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  101936. }
  101937. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  101938. if (!this._imageProcessingConfiguration.isReady()) {
  101939. return false;
  101940. }
  101941. this._imageProcessingConfiguration.prepareDefines(defines);
  101942. }
  101943. // Misc.
  101944. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  101945. // Values that need to be evaluated on every frame
  101946. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  101947. // Attribs
  101948. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  101949. if (mesh) {
  101950. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  101951. mesh.createNormals(true);
  101952. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  101953. }
  101954. }
  101955. }
  101956. // Get correct effect
  101957. if (defines.isDirty) {
  101958. defines.markAsProcessed();
  101959. scene.resetCachedMaterial();
  101960. // Fallbacks
  101961. var fallbacks = new BABYLON.EffectFallbacks();
  101962. if (defines.FOG) {
  101963. fallbacks.addFallback(0, "FOG");
  101964. }
  101965. if (defines.POINTSIZE) {
  101966. fallbacks.addFallback(1, "POINTSIZE");
  101967. }
  101968. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  101969. if (defines.NUM_BONE_INFLUENCERS > 0) {
  101970. fallbacks.addCPUSkinningFallback(0, mesh);
  101971. }
  101972. //Attributes
  101973. var attribs = [BABYLON.VertexBuffer.PositionKind];
  101974. if (defines.NORMAL) {
  101975. attribs.push(BABYLON.VertexBuffer.NormalKind);
  101976. }
  101977. if (defines.UV1) {
  101978. attribs.push(BABYLON.VertexBuffer.UVKind);
  101979. }
  101980. if (defines.UV2) {
  101981. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  101982. }
  101983. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  101984. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  101985. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  101986. "vFogInfos", "vFogColor", "pointSize",
  101987. "vClipPlane", "mBones",
  101988. "vPrimaryColor", "vPrimaryColorShadow",
  101989. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  101990. "shadowLevel", "alpha",
  101991. "vBackgroundCenter", "vReflectionControl",
  101992. "vDiffuseInfos", "diffuseMatrix",
  101993. ];
  101994. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  101995. var uniformBuffers = ["Material", "Scene"];
  101996. if (BABYLON.ImageProcessingConfiguration) {
  101997. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  101998. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  101999. }
  102000. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  102001. uniformsNames: uniforms,
  102002. uniformBuffersNames: uniformBuffers,
  102003. samplers: samplers,
  102004. defines: defines,
  102005. maxSimultaneousLights: this._maxSimultaneousLights
  102006. });
  102007. var onCompiled = function (effect) {
  102008. if (_this.onCompiled) {
  102009. _this.onCompiled(effect);
  102010. }
  102011. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  102012. };
  102013. var join = defines.toString();
  102014. subMesh.setEffect(scene.getEngine().createEffect("background", {
  102015. attributes: attribs,
  102016. uniformsNames: uniforms,
  102017. uniformBuffersNames: uniformBuffers,
  102018. samplers: samplers,
  102019. defines: join,
  102020. fallbacks: fallbacks,
  102021. onCompiled: onCompiled,
  102022. onError: this.onError,
  102023. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  102024. }, engine), defines);
  102025. this.buildUniformLayout();
  102026. }
  102027. if (!subMesh.effect || !subMesh.effect.isReady()) {
  102028. return false;
  102029. }
  102030. defines._renderId = scene.getRenderId();
  102031. this._wasPreviouslyReady = true;
  102032. return true;
  102033. };
  102034. /**
  102035. * Compute the primary color according to the chosen perceptual color.
  102036. */
  102037. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  102038. if (!this.__perceptualColor) {
  102039. return;
  102040. }
  102041. this._primaryColor.copyFrom(this.__perceptualColor);
  102042. // Revert gamma space.
  102043. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  102044. // Revert image processing configuration.
  102045. if (this._imageProcessingConfiguration) {
  102046. // Revert Exposure.
  102047. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  102048. }
  102049. this._computePrimaryColors();
  102050. };
  102051. /**
  102052. * Compute the highlights and shadow colors according to their chosen levels.
  102053. */
  102054. BackgroundMaterial.prototype._computePrimaryColors = function () {
  102055. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  102056. return;
  102057. }
  102058. // Find the highlight color based on the configuration.
  102059. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  102060. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  102061. // Find the shadow color based on the configuration.
  102062. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  102063. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  102064. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  102065. };
  102066. /**
  102067. * Build the uniform buffer used in the material.
  102068. */
  102069. BackgroundMaterial.prototype.buildUniformLayout = function () {
  102070. // Order is important !
  102071. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  102072. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  102073. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  102074. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  102075. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  102076. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  102077. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  102078. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  102079. this._uniformBuffer.addUniform("pointSize", 1);
  102080. this._uniformBuffer.addUniform("shadowLevel", 1);
  102081. this._uniformBuffer.addUniform("alpha", 1);
  102082. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  102083. this._uniformBuffer.addUniform("vReflectionControl", 4);
  102084. this._uniformBuffer.create();
  102085. };
  102086. /**
  102087. * Unbind the material.
  102088. */
  102089. BackgroundMaterial.prototype.unbind = function () {
  102090. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  102091. this._uniformBuffer.setTexture("diffuseSampler", null);
  102092. }
  102093. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  102094. this._uniformBuffer.setTexture("reflectionSampler", null);
  102095. }
  102096. _super.prototype.unbind.call(this);
  102097. };
  102098. /**
  102099. * Bind only the world matrix to the material.
  102100. * @param world The world matrix to bind.
  102101. */
  102102. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  102103. this._activeEffect.setMatrix("world", world);
  102104. };
  102105. /**
  102106. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  102107. * @param world The world matrix to bind.
  102108. * @param subMesh The submesh to bind for.
  102109. */
  102110. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  102111. var scene = this.getScene();
  102112. var defines = subMesh._materialDefines;
  102113. if (!defines) {
  102114. return;
  102115. }
  102116. var effect = subMesh.effect;
  102117. if (!effect) {
  102118. return;
  102119. }
  102120. this._activeEffect = effect;
  102121. // Matrices
  102122. this.bindOnlyWorldMatrix(world);
  102123. // Bones
  102124. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  102125. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  102126. if (mustRebind) {
  102127. this._uniformBuffer.bindToEffect(effect, "Material");
  102128. this.bindViewProjection(effect);
  102129. var reflectionTexture = this._reflectionTexture;
  102130. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  102131. // Texture uniforms
  102132. if (scene.texturesEnabled) {
  102133. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102134. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  102135. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  102136. }
  102137. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102138. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  102139. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  102140. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  102141. }
  102142. }
  102143. if (this.shadowLevel > 0) {
  102144. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  102145. }
  102146. this._uniformBuffer.updateFloat("alpha", this.alpha);
  102147. // Point size
  102148. if (this.pointsCloud) {
  102149. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  102150. }
  102151. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  102152. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  102153. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  102154. }
  102155. else {
  102156. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  102157. }
  102158. }
  102159. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  102160. // Textures
  102161. if (scene.texturesEnabled) {
  102162. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102163. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  102164. }
  102165. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102166. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  102167. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  102168. }
  102169. else if (!defines.REFLECTIONBLUR) {
  102170. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  102171. }
  102172. else {
  102173. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  102174. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  102175. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  102176. }
  102177. if (defines.REFLECTIONFRESNEL) {
  102178. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  102179. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  102180. }
  102181. }
  102182. }
  102183. // Clip plane
  102184. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  102185. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  102186. }
  102187. if (mustRebind || !this.isFrozen) {
  102188. if (scene.lightsEnabled) {
  102189. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  102190. }
  102191. // View
  102192. this.bindView(effect);
  102193. // Fog
  102194. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  102195. // image processing
  102196. if (this._imageProcessingConfiguration) {
  102197. this._imageProcessingConfiguration.bind(this._activeEffect);
  102198. }
  102199. }
  102200. this._uniformBuffer.update();
  102201. this._afterBind(mesh, this._activeEffect);
  102202. };
  102203. /**
  102204. * Dispose the material.
  102205. * @param forceDisposeEffect Force disposal of the associated effect.
  102206. * @param forceDisposeTextures Force disposal of the associated textures.
  102207. */
  102208. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  102209. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  102210. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  102211. if (forceDisposeTextures) {
  102212. if (this.diffuseTexture) {
  102213. this.diffuseTexture.dispose();
  102214. }
  102215. if (this.reflectionTexture) {
  102216. this.reflectionTexture.dispose();
  102217. }
  102218. }
  102219. this._renderTargets.dispose();
  102220. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  102221. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  102222. }
  102223. _super.prototype.dispose.call(this, forceDisposeEffect);
  102224. };
  102225. /**
  102226. * Clones the material.
  102227. * @param name The cloned name.
  102228. * @returns The cloned material.
  102229. */
  102230. BackgroundMaterial.prototype.clone = function (name) {
  102231. var _this = this;
  102232. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  102233. };
  102234. /**
  102235. * Serializes the current material to its JSON representation.
  102236. * @returns The JSON representation.
  102237. */
  102238. BackgroundMaterial.prototype.serialize = function () {
  102239. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  102240. serializationObject.customType = "BABYLON.BackgroundMaterial";
  102241. return serializationObject;
  102242. };
  102243. /**
  102244. * Gets the class name of the material
  102245. * @returns "BackgroundMaterial"
  102246. */
  102247. BackgroundMaterial.prototype.getClassName = function () {
  102248. return "BackgroundMaterial";
  102249. };
  102250. /**
  102251. * Parse a JSON input to create back a background material.
  102252. * @param source The JSON data to parse
  102253. * @param scene The scene to create the parsed material in
  102254. * @param rootUrl The root url of the assets the material depends upon
  102255. * @returns the instantiated BackgroundMaterial.
  102256. */
  102257. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  102258. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  102259. };
  102260. /**
  102261. * Standard reflectance value at parallel view angle.
  102262. */
  102263. BackgroundMaterial.StandardReflectance0 = 0.05;
  102264. /**
  102265. * Standard reflectance value at grazing angle.
  102266. */
  102267. BackgroundMaterial.StandardReflectance90 = 0.5;
  102268. __decorate([
  102269. BABYLON.serializeAsColor3()
  102270. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  102271. __decorate([
  102272. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102273. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  102274. __decorate([
  102275. BABYLON.serializeAsColor3()
  102276. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  102277. __decorate([
  102278. BABYLON.serialize()
  102279. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  102280. __decorate([
  102281. BABYLON.serialize()
  102282. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  102283. __decorate([
  102284. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102285. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  102286. __decorate([
  102287. BABYLON.serializeAsTexture()
  102288. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  102289. __decorate([
  102290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102291. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  102292. __decorate([
  102293. BABYLON.serialize()
  102294. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  102295. __decorate([
  102296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102297. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  102298. __decorate([
  102299. BABYLON.serializeAsTexture()
  102300. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  102301. __decorate([
  102302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102303. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  102304. __decorate([
  102305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102306. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  102307. __decorate([
  102308. BABYLON.serialize()
  102309. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  102310. __decorate([
  102311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102312. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  102313. __decorate([
  102314. BABYLON.serializeAsVector3()
  102315. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  102316. __decorate([
  102317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102318. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  102319. __decorate([
  102320. BABYLON.serialize()
  102321. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  102322. __decorate([
  102323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102324. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  102325. __decorate([
  102326. BABYLON.serialize()
  102327. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  102328. __decorate([
  102329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102330. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  102331. __decorate([
  102332. BABYLON.serialize()
  102333. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  102334. __decorate([
  102335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102336. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  102337. __decorate([
  102338. BABYLON.serialize()
  102339. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  102340. __decorate([
  102341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102342. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  102343. __decorate([
  102344. BABYLON.serialize()
  102345. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  102346. __decorate([
  102347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102348. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  102349. __decorate([
  102350. BABYLON.serialize()
  102351. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  102352. __decorate([
  102353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102354. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  102355. __decorate([
  102356. BABYLON.serialize()
  102357. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  102358. __decorate([
  102359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102360. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  102361. __decorate([
  102362. BABYLON.serialize()
  102363. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  102364. __decorate([
  102365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102366. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  102367. __decorate([
  102368. BABYLON.serialize()
  102369. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  102370. __decorate([
  102371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102372. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  102373. __decorate([
  102374. BABYLON.serializeAsImageProcessingConfiguration()
  102375. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  102376. return BackgroundMaterial;
  102377. }(BABYLON.PushMaterial));
  102378. BABYLON.BackgroundMaterial = BackgroundMaterial;
  102379. })(BABYLON || (BABYLON = {}));
  102380. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  102381. var __assign = (this && this.__assign) || Object.assign || function(t) {
  102382. for (var s, i = 1, n = arguments.length; i < n; i++) {
  102383. s = arguments[i];
  102384. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  102385. t[p] = s[p];
  102386. }
  102387. return t;
  102388. };
  102389. var BABYLON;
  102390. (function (BABYLON) {
  102391. /**
  102392. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  102393. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  102394. * It also helps with the default setup of your imageProcessing configuration.
  102395. */
  102396. var EnvironmentHelper = /** @class */ (function () {
  102397. /**
  102398. * constructor
  102399. * @param options
  102400. * @param scene The scene to add the material to
  102401. */
  102402. function EnvironmentHelper(options, scene) {
  102403. var _this = this;
  102404. this._errorHandler = function (message, exception) {
  102405. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  102406. };
  102407. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  102408. this._scene = scene;
  102409. this.onErrorObservable = new BABYLON.Observable();
  102410. this._setupBackground();
  102411. this._setupImageProcessing();
  102412. }
  102413. /**
  102414. * Creates the default options for the helper.
  102415. */
  102416. EnvironmentHelper._getDefaultOptions = function () {
  102417. return {
  102418. createGround: true,
  102419. groundSize: 15,
  102420. groundTexture: this._groundTextureCDNUrl,
  102421. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102422. groundOpacity: 0.9,
  102423. enableGroundShadow: true,
  102424. groundShadowLevel: 0.5,
  102425. enableGroundMirror: false,
  102426. groundMirrorSizeRatio: 0.3,
  102427. groundMirrorBlurKernel: 64,
  102428. groundMirrorAmount: 1,
  102429. groundMirrorFresnelWeight: 1,
  102430. groundMirrorFallOffDistance: 0,
  102431. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  102432. groundYBias: 0.00001,
  102433. createSkybox: true,
  102434. skyboxSize: 20,
  102435. skyboxTexture: this._skyboxTextureCDNUrl,
  102436. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102437. backgroundYRotation: 0,
  102438. sizeAuto: true,
  102439. rootPosition: BABYLON.Vector3.Zero(),
  102440. setupImageProcessing: true,
  102441. environmentTexture: this._environmentTextureCDNUrl,
  102442. cameraExposure: 0.8,
  102443. cameraContrast: 1.2,
  102444. toneMappingEnabled: true,
  102445. };
  102446. };
  102447. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  102448. /**
  102449. * Gets the root mesh created by the helper.
  102450. */
  102451. get: function () {
  102452. return this._rootMesh;
  102453. },
  102454. enumerable: true,
  102455. configurable: true
  102456. });
  102457. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  102458. /**
  102459. * Gets the skybox created by the helper.
  102460. */
  102461. get: function () {
  102462. return this._skybox;
  102463. },
  102464. enumerable: true,
  102465. configurable: true
  102466. });
  102467. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  102468. /**
  102469. * Gets the skybox texture created by the helper.
  102470. */
  102471. get: function () {
  102472. return this._skyboxTexture;
  102473. },
  102474. enumerable: true,
  102475. configurable: true
  102476. });
  102477. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  102478. /**
  102479. * Gets the skybox material created by the helper.
  102480. */
  102481. get: function () {
  102482. return this._skyboxMaterial;
  102483. },
  102484. enumerable: true,
  102485. configurable: true
  102486. });
  102487. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  102488. /**
  102489. * Gets the ground mesh created by the helper.
  102490. */
  102491. get: function () {
  102492. return this._ground;
  102493. },
  102494. enumerable: true,
  102495. configurable: true
  102496. });
  102497. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  102498. /**
  102499. * Gets the ground texture created by the helper.
  102500. */
  102501. get: function () {
  102502. return this._groundTexture;
  102503. },
  102504. enumerable: true,
  102505. configurable: true
  102506. });
  102507. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  102508. /**
  102509. * Gets the ground mirror created by the helper.
  102510. */
  102511. get: function () {
  102512. return this._groundMirror;
  102513. },
  102514. enumerable: true,
  102515. configurable: true
  102516. });
  102517. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  102518. /**
  102519. * Gets the ground mirror render list to helps pushing the meshes
  102520. * you wish in the ground reflection.
  102521. */
  102522. get: function () {
  102523. if (this._groundMirror) {
  102524. return this._groundMirror.renderList;
  102525. }
  102526. return null;
  102527. },
  102528. enumerable: true,
  102529. configurable: true
  102530. });
  102531. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  102532. /**
  102533. * Gets the ground material created by the helper.
  102534. */
  102535. get: function () {
  102536. return this._groundMaterial;
  102537. },
  102538. enumerable: true,
  102539. configurable: true
  102540. });
  102541. /**
  102542. * Updates the background according to the new options
  102543. * @param options
  102544. */
  102545. EnvironmentHelper.prototype.updateOptions = function (options) {
  102546. var newOptions = __assign({}, this._options, options);
  102547. if (this._ground && !newOptions.createGround) {
  102548. this._ground.dispose();
  102549. this._ground = null;
  102550. }
  102551. if (this._groundMaterial && !newOptions.createGround) {
  102552. this._groundMaterial.dispose();
  102553. this._groundMaterial = null;
  102554. }
  102555. if (this._groundTexture) {
  102556. if (this._options.groundTexture != newOptions.groundTexture) {
  102557. this._groundTexture.dispose();
  102558. this._groundTexture = null;
  102559. }
  102560. }
  102561. if (this._skybox && !newOptions.createSkybox) {
  102562. this._skybox.dispose();
  102563. this._skybox = null;
  102564. }
  102565. if (this._skyboxMaterial && !newOptions.createSkybox) {
  102566. this._skyboxMaterial.dispose();
  102567. this._skyboxMaterial = null;
  102568. }
  102569. if (this._skyboxTexture) {
  102570. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  102571. this._skyboxTexture.dispose();
  102572. this._skyboxTexture = null;
  102573. }
  102574. }
  102575. if (this._groundMirror && !newOptions.enableGroundMirror) {
  102576. this._groundMirror.dispose();
  102577. this._groundMirror = null;
  102578. }
  102579. if (this._scene.environmentTexture) {
  102580. if (this._options.environmentTexture != newOptions.environmentTexture) {
  102581. this._scene.environmentTexture.dispose();
  102582. }
  102583. }
  102584. this._options = newOptions;
  102585. this._setupBackground();
  102586. this._setupImageProcessing();
  102587. };
  102588. /**
  102589. * Sets the primary color of all the available elements.
  102590. * @param color the main color to affect to the ground and the background
  102591. */
  102592. EnvironmentHelper.prototype.setMainColor = function (color) {
  102593. if (this.groundMaterial) {
  102594. this.groundMaterial.primaryColor = color;
  102595. }
  102596. if (this.skyboxMaterial) {
  102597. this.skyboxMaterial.primaryColor = color;
  102598. }
  102599. if (this.groundMirror) {
  102600. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  102601. }
  102602. };
  102603. /**
  102604. * Setup the image processing according to the specified options.
  102605. */
  102606. EnvironmentHelper.prototype._setupImageProcessing = function () {
  102607. if (this._options.setupImageProcessing) {
  102608. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  102609. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  102610. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  102611. this._setupEnvironmentTexture();
  102612. }
  102613. };
  102614. /**
  102615. * Setup the environment texture according to the specified options.
  102616. */
  102617. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  102618. if (this._scene.environmentTexture) {
  102619. return;
  102620. }
  102621. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  102622. this._scene.environmentTexture = this._options.environmentTexture;
  102623. return;
  102624. }
  102625. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  102626. this._scene.environmentTexture = environmentTexture;
  102627. };
  102628. /**
  102629. * Setup the background according to the specified options.
  102630. */
  102631. EnvironmentHelper.prototype._setupBackground = function () {
  102632. if (!this._rootMesh) {
  102633. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  102634. }
  102635. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  102636. var sceneSize = this._getSceneSize();
  102637. if (this._options.createGround) {
  102638. this._setupGround(sceneSize);
  102639. this._setupGroundMaterial();
  102640. this._setupGroundDiffuseTexture();
  102641. if (this._options.enableGroundMirror) {
  102642. this._setupGroundMirrorTexture(sceneSize);
  102643. }
  102644. this._setupMirrorInGroundMaterial();
  102645. }
  102646. if (this._options.createSkybox) {
  102647. this._setupSkybox(sceneSize);
  102648. this._setupSkyboxMaterial();
  102649. this._setupSkyboxReflectionTexture();
  102650. }
  102651. this._rootMesh.position.x = sceneSize.rootPosition.x;
  102652. this._rootMesh.position.z = sceneSize.rootPosition.z;
  102653. this._rootMesh.position.y = sceneSize.rootPosition.y;
  102654. };
  102655. /**
  102656. * Get the scene sizes according to the setup.
  102657. */
  102658. EnvironmentHelper.prototype._getSceneSize = function () {
  102659. var _this = this;
  102660. var groundSize = this._options.groundSize;
  102661. var skyboxSize = this._options.skyboxSize;
  102662. var rootPosition = this._options.rootPosition;
  102663. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  102664. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102665. }
  102666. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  102667. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  102668. });
  102669. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  102670. if (this._options.sizeAuto) {
  102671. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  102672. this._scene.activeCamera.upperRadiusLimit) {
  102673. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  102674. skyboxSize = groundSize;
  102675. }
  102676. var sceneDiagonalLenght = sceneDiagonal.length();
  102677. if (sceneDiagonalLenght > groundSize) {
  102678. groundSize = sceneDiagonalLenght * 2;
  102679. skyboxSize = groundSize;
  102680. }
  102681. // 10 % bigger.
  102682. groundSize *= 1.1;
  102683. skyboxSize *= 1.5;
  102684. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  102685. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  102686. }
  102687. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102688. };
  102689. /**
  102690. * Setup the ground according to the specified options.
  102691. */
  102692. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  102693. var _this = this;
  102694. if (!this._ground || this._ground.isDisposed()) {
  102695. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  102696. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  102697. this._ground.parent = this._rootMesh;
  102698. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  102699. }
  102700. this._ground.receiveShadows = this._options.enableGroundShadow;
  102701. };
  102702. /**
  102703. * Setup the ground material according to the specified options.
  102704. */
  102705. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  102706. if (!this._groundMaterial) {
  102707. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  102708. }
  102709. this._groundMaterial.alpha = this._options.groundOpacity;
  102710. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  102711. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  102712. this._groundMaterial.primaryColor = this._options.groundColor;
  102713. this._groundMaterial.useRGBColor = false;
  102714. this._groundMaterial.enableNoise = true;
  102715. if (this._ground) {
  102716. this._ground.material = this._groundMaterial;
  102717. }
  102718. };
  102719. /**
  102720. * Setup the ground diffuse texture according to the specified options.
  102721. */
  102722. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  102723. if (!this._groundMaterial) {
  102724. return;
  102725. }
  102726. if (this._groundTexture) {
  102727. return;
  102728. }
  102729. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  102730. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  102731. return;
  102732. }
  102733. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102734. diffuseTexture.gammaSpace = false;
  102735. diffuseTexture.hasAlpha = true;
  102736. this._groundMaterial.diffuseTexture = diffuseTexture;
  102737. };
  102738. /**
  102739. * Setup the ground mirror texture according to the specified options.
  102740. */
  102741. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  102742. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102743. if (!this._groundMirror) {
  102744. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  102745. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  102746. this._groundMirror.anisotropicFilteringLevel = 1;
  102747. this._groundMirror.wrapU = wrapping;
  102748. this._groundMirror.wrapV = wrapping;
  102749. this._groundMirror.gammaSpace = false;
  102750. if (this._groundMirror.renderList) {
  102751. for (var i = 0; i < this._scene.meshes.length; i++) {
  102752. var mesh = this._scene.meshes[i];
  102753. if (mesh !== this._ground &&
  102754. mesh !== this._skybox &&
  102755. mesh !== this._rootMesh) {
  102756. this._groundMirror.renderList.push(mesh);
  102757. }
  102758. }
  102759. }
  102760. }
  102761. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  102762. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  102763. };
  102764. /**
  102765. * Setup the ground to receive the mirror texture.
  102766. */
  102767. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  102768. if (this._groundMaterial) {
  102769. this._groundMaterial.reflectionTexture = this._groundMirror;
  102770. this._groundMaterial.reflectionFresnel = true;
  102771. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  102772. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  102773. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  102774. }
  102775. };
  102776. /**
  102777. * Setup the skybox according to the specified options.
  102778. */
  102779. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  102780. var _this = this;
  102781. if (!this._skybox || this._skybox.isDisposed()) {
  102782. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  102783. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  102784. }
  102785. this._skybox.parent = this._rootMesh;
  102786. };
  102787. /**
  102788. * Setup the skybox material according to the specified options.
  102789. */
  102790. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  102791. if (!this._skybox) {
  102792. return;
  102793. }
  102794. if (!this._skyboxMaterial) {
  102795. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  102796. }
  102797. this._skyboxMaterial.useRGBColor = false;
  102798. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  102799. this._skyboxMaterial.enableNoise = true;
  102800. this._skybox.material = this._skyboxMaterial;
  102801. };
  102802. /**
  102803. * Setup the skybox reflection texture according to the specified options.
  102804. */
  102805. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  102806. if (!this._skyboxMaterial) {
  102807. return;
  102808. }
  102809. if (this._skyboxTexture) {
  102810. return;
  102811. }
  102812. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  102813. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  102814. return;
  102815. }
  102816. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102817. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  102818. this._skyboxTexture.gammaSpace = false;
  102819. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  102820. };
  102821. /**
  102822. * Dispose all the elements created by the Helper.
  102823. */
  102824. EnvironmentHelper.prototype.dispose = function () {
  102825. if (this._groundMaterial) {
  102826. this._groundMaterial.dispose(true, true);
  102827. }
  102828. if (this._skyboxMaterial) {
  102829. this._skyboxMaterial.dispose(true, true);
  102830. }
  102831. this._rootMesh.dispose(false);
  102832. };
  102833. /**
  102834. * Default ground texture URL.
  102835. */
  102836. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  102837. /**
  102838. * Default skybox texture URL.
  102839. */
  102840. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  102841. /**
  102842. * Default environment texture URL.
  102843. */
  102844. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  102845. return EnvironmentHelper;
  102846. }());
  102847. BABYLON.EnvironmentHelper = EnvironmentHelper;
  102848. })(BABYLON || (BABYLON = {}));
  102849. //# sourceMappingURL=babylon.environmentHelper.js.map
  102850. var BABYLON;
  102851. (function (BABYLON) {
  102852. /** Internal class used to store shapes for emitters */
  102853. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  102854. function ParticleSystemSetEmitterCreationOptions() {
  102855. }
  102856. return ParticleSystemSetEmitterCreationOptions;
  102857. }());
  102858. /**
  102859. * Represents a set of particle systems working together to create a specific effect
  102860. */
  102861. var ParticleSystemSet = /** @class */ (function () {
  102862. function ParticleSystemSet() {
  102863. /**
  102864. * Gets the particle system list
  102865. */
  102866. this.systems = new Array();
  102867. }
  102868. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  102869. /**
  102870. * Gets the emitter node used with this set
  102871. */
  102872. get: function () {
  102873. return this._emitterNode;
  102874. },
  102875. enumerable: true,
  102876. configurable: true
  102877. });
  102878. /**
  102879. * Creates a new emitter mesh as a sphere
  102880. * @param options defines the options used to create the sphere
  102881. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  102882. * @param scene defines the hosting scene
  102883. */
  102884. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  102885. if (this._emitterNode) {
  102886. this._emitterNode.dispose();
  102887. }
  102888. this._emitterCreationOptions = {
  102889. kind: "Sphere",
  102890. options: options,
  102891. renderingGroupId: renderingGroupId
  102892. };
  102893. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  102894. emitterMesh.renderingGroupId = renderingGroupId;
  102895. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  102896. material.emissiveColor = options.color;
  102897. emitterMesh.material = material;
  102898. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102899. var system = _a[_i];
  102900. system.emitter = emitterMesh;
  102901. }
  102902. this._emitterNode = emitterMesh;
  102903. };
  102904. /**
  102905. * Starts all particle systems of the set
  102906. * @param emitter defines an optional mesh to use as emitter for the particle systems
  102907. */
  102908. ParticleSystemSet.prototype.start = function (emitter) {
  102909. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102910. var system = _a[_i];
  102911. if (emitter) {
  102912. system.emitter = emitter;
  102913. }
  102914. system.start();
  102915. }
  102916. };
  102917. /**
  102918. * Release all associated resources
  102919. */
  102920. ParticleSystemSet.prototype.dispose = function () {
  102921. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102922. var system = _a[_i];
  102923. system.dispose();
  102924. }
  102925. this.systems = [];
  102926. if (this._emitterNode) {
  102927. this._emitterNode.dispose();
  102928. this._emitterNode = null;
  102929. }
  102930. };
  102931. /**
  102932. * Serialize the set into a JSON compatible object
  102933. * @returns a JSON compatible representation of the set
  102934. */
  102935. ParticleSystemSet.prototype.serialize = function () {
  102936. var result = {};
  102937. result.systems = [];
  102938. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102939. var system = _a[_i];
  102940. result.systems.push(system.serialize());
  102941. }
  102942. if (this._emitterNode) {
  102943. result.emitter = this._emitterCreationOptions;
  102944. }
  102945. return result;
  102946. };
  102947. /**
  102948. * Parse a new ParticleSystemSet from a serialized source
  102949. * @param data defines a JSON compatible representation of the set
  102950. * @param scene defines the hosting scene
  102951. * @param gpu defines if we want GPU particles or CPU particles
  102952. * @returns a new ParticleSystemSet
  102953. */
  102954. ParticleSystemSet.Parse = function (data, scene, gpu) {
  102955. if (gpu === void 0) { gpu = false; }
  102956. var result = new ParticleSystemSet();
  102957. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  102958. scene = scene || BABYLON.Engine.LastCreatedScene;
  102959. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  102960. var system = _a[_i];
  102961. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  102962. }
  102963. if (data.emitter) {
  102964. var options = data.emitter.options;
  102965. switch (data.emitter.kind) {
  102966. case "Sphere":
  102967. result.setEmitterAsSphere({
  102968. diameter: options.diameter,
  102969. segments: options.segments,
  102970. color: BABYLON.Color3.FromArray(options.color)
  102971. }, data.emitter.renderingGroupId, scene);
  102972. break;
  102973. }
  102974. }
  102975. return result;
  102976. };
  102977. return ParticleSystemSet;
  102978. }());
  102979. BABYLON.ParticleSystemSet = ParticleSystemSet;
  102980. })(BABYLON || (BABYLON = {}));
  102981. //# sourceMappingURL=babylon.particleSystemSet.js.map
  102982. var BABYLON;
  102983. (function (BABYLON) {
  102984. /**
  102985. * This class is made for on one-liner static method to help creating particle system set.
  102986. */
  102987. var ParticleHelper = /** @class */ (function () {
  102988. function ParticleHelper() {
  102989. }
  102990. /**
  102991. * This is the main static method (one-liner) of this helper to create different particle systems
  102992. * @param type This string represents the type to the particle system to create
  102993. * @param scene The scene where the particle system should live
  102994. * @param gpu If the system will use gpu
  102995. * @returns the ParticleSystemSet created
  102996. */
  102997. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  102998. if (gpu === void 0) { gpu = false; }
  102999. if (!scene) {
  103000. scene = BABYLON.Engine.LastCreatedScene;
  103001. ;
  103002. }
  103003. var token = {};
  103004. scene._addPendingData(token);
  103005. return new Promise(function (resolve, reject) {
  103006. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  103007. scene._removePendingData(token);
  103008. return reject("Particle system with GPU is not supported.");
  103009. }
  103010. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  103011. scene._removePendingData(token);
  103012. var newData = JSON.parse(data.toString());
  103013. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  103014. }, undefined, undefined, undefined, function (req, exception) {
  103015. scene._removePendingData(token);
  103016. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  103017. });
  103018. });
  103019. };
  103020. /**
  103021. * Static function used to export a particle system to a ParticleSystemSet variable.
  103022. * Please note that the emitter shape is not exported
  103023. * @param system defines the particle systems to export
  103024. */
  103025. ParticleHelper.ExportSet = function (systems) {
  103026. var set = new BABYLON.ParticleSystemSet();
  103027. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  103028. var system = systems_1[_i];
  103029. set.systems.push(system);
  103030. }
  103031. return set;
  103032. };
  103033. /**
  103034. * Gets or sets base Assets URL
  103035. */
  103036. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  103037. return ParticleHelper;
  103038. }());
  103039. BABYLON.ParticleHelper = ParticleHelper;
  103040. })(BABYLON || (BABYLON = {}));
  103041. //# sourceMappingURL=babylon.particleHelper.js.map
  103042. var BABYLON;
  103043. (function (BABYLON) {
  103044. /**
  103045. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  103046. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  103047. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  103048. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103049. */
  103050. var VideoDome = /** @class */ (function (_super) {
  103051. __extends(VideoDome, _super);
  103052. /**
  103053. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  103054. * @param name Element's name, child elements will append suffixes for their own names.
  103055. * @param urlsOrVideo defines the url(s) or the video element to use
  103056. * @param options An object containing optional or exposed sub element properties
  103057. */
  103058. function VideoDome(name, urlsOrVideo, options, scene) {
  103059. var _this = _super.call(this, name, scene) || this;
  103060. _this._useDirectMapping = false;
  103061. // set defaults and manage values
  103062. name = name || "videoDome";
  103063. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  103064. options.clickToPlay = Boolean(options.clickToPlay);
  103065. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  103066. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  103067. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  103068. if (options.useDirectMapping === undefined) {
  103069. _this._useDirectMapping = true;
  103070. }
  103071. else {
  103072. _this._useDirectMapping = options.useDirectMapping;
  103073. }
  103074. // create
  103075. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  103076. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  103077. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  103078. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  103079. // configure material
  103080. material.useEquirectangularFOV = true;
  103081. material.fovMultiplier = 1.0;
  103082. material.opacityFresnel = false;
  103083. if (_this._useDirectMapping) {
  103084. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103085. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103086. material.diffuseTexture = texture;
  103087. }
  103088. else {
  103089. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  103090. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103091. material.reflectionTexture = texture;
  103092. }
  103093. // configure mesh
  103094. _this._mesh.material = material;
  103095. _this._mesh.parent = _this;
  103096. // optional configuration
  103097. if (options.clickToPlay) {
  103098. scene.onPointerUp = function () {
  103099. _this._videoTexture.video.play();
  103100. };
  103101. }
  103102. return _this;
  103103. }
  103104. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  103105. /**
  103106. * Gets the video texture being displayed on the sphere
  103107. */
  103108. get: function () {
  103109. return this._videoTexture;
  103110. },
  103111. enumerable: true,
  103112. configurable: true
  103113. });
  103114. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  103115. /**
  103116. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103117. * Also see the options.resolution property.
  103118. */
  103119. get: function () {
  103120. return this._material.fovMultiplier;
  103121. },
  103122. set: function (value) {
  103123. this._material.fovMultiplier = value;
  103124. },
  103125. enumerable: true,
  103126. configurable: true
  103127. });
  103128. /**
  103129. * Releases resources associated with this node.
  103130. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  103131. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  103132. */
  103133. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  103134. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  103135. this._videoTexture.dispose();
  103136. this._mesh.dispose();
  103137. this._material.dispose();
  103138. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  103139. };
  103140. return VideoDome;
  103141. }(BABYLON.Node));
  103142. BABYLON.VideoDome = VideoDome;
  103143. })(BABYLON || (BABYLON = {}));
  103144. //# sourceMappingURL=babylon.videoDome.js.map
  103145. var BABYLON;
  103146. (function (BABYLON) {
  103147. /**
  103148. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  103149. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  103150. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  103151. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103152. */
  103153. var PhotoDome = /** @class */ (function (_super) {
  103154. __extends(PhotoDome, _super);
  103155. /**
  103156. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  103157. * @param name Element's name, child elements will append suffixes for their own names.
  103158. * @param urlsOfPhoto define the url of the photo to display
  103159. * @param options An object containing optional or exposed sub element properties
  103160. */
  103161. function PhotoDome(name, urlOfPhoto, options, scene) {
  103162. var _this = _super.call(this, name, scene) || this;
  103163. _this._useDirectMapping = false;
  103164. // set defaults and manage values
  103165. name = name || "photoDome";
  103166. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  103167. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  103168. if (options.useDirectMapping === undefined) {
  103169. _this._useDirectMapping = true;
  103170. }
  103171. else {
  103172. _this._useDirectMapping = options.useDirectMapping;
  103173. }
  103174. // create
  103175. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  103176. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  103177. // configure material
  103178. material.opacityFresnel = false;
  103179. material.useEquirectangularFOV = true;
  103180. material.fovMultiplier = 1.0;
  103181. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  103182. // configure mesh
  103183. _this._mesh.material = material;
  103184. _this._mesh.parent = _this;
  103185. return _this;
  103186. }
  103187. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  103188. /**
  103189. * Gets or sets the texture being displayed on the sphere
  103190. */
  103191. get: function () {
  103192. return this._photoTexture;
  103193. },
  103194. set: function (value) {
  103195. if (this._photoTexture === value) {
  103196. return;
  103197. }
  103198. this._photoTexture = value;
  103199. if (this._useDirectMapping) {
  103200. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103201. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103202. this._material.diffuseTexture = this._photoTexture;
  103203. }
  103204. else {
  103205. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  103206. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103207. this._material.reflectionTexture = this._photoTexture;
  103208. }
  103209. },
  103210. enumerable: true,
  103211. configurable: true
  103212. });
  103213. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  103214. /**
  103215. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103216. * Also see the options.resolution property.
  103217. */
  103218. get: function () {
  103219. return this._material.fovMultiplier;
  103220. },
  103221. set: function (value) {
  103222. this._material.fovMultiplier = value;
  103223. },
  103224. enumerable: true,
  103225. configurable: true
  103226. });
  103227. /**
  103228. * Releases resources associated with this node.
  103229. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  103230. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  103231. */
  103232. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  103233. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  103234. this._photoTexture.dispose();
  103235. this._mesh.dispose();
  103236. this._material.dispose();
  103237. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  103238. };
  103239. return PhotoDome;
  103240. }(BABYLON.Node));
  103241. BABYLON.PhotoDome = PhotoDome;
  103242. })(BABYLON || (BABYLON = {}));
  103243. //# sourceMappingURL=babylon.photoDome.js.map
  103244. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h;\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction;\n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","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"};
  103245. 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};"};